zoukankan      html  css  js  c++  java
  • 对于异步编程Await和Async的理解

     public class AsyncInSync
        {
            /// <summary>
            /// 同步代码里有异步代码
            /// 
            /// 
            /// 结果
            /// Main Thread Before DelayAsync:1
            /// DelayAsync Before Await Thread ID:1
            /// DelayReturnTaskAsync Before Await Thread ID:1
            /// Main Thread After DelayAsync:1
            /// DelayReturnTaskAsync After Await Thread ID:4
            /// DelayAsync After Await Thread ID:4
            /// </summary>
            static public void Test()
            {
                Console.WriteLine("Main Thread Before DelayAsync:" + Thread.CurrentThread.ManagedThreadId);
    
                DelayAsync(10000);
    
                Console.WriteLine("Main Thread After DelayAsync:" + Thread.CurrentThread.ManagedThreadId);
            }
    
            /// <summary>
            /// 异步代码里有异步代码
            /// 
            /// 
            /// 异步方法里有同步代码执行顺序:
            /// 1 当前线程:进入DelayAsync方法
            /// 2 当前线程:同步执行Thread.Sleep(1000);
            /// 3 当前线程:(发现async里有await)当前线程返回DelayAsync的调用方向下执行。
            /// 4 其他线程:执行await后的函数和Thread.Sleep(2000);)
            ///  
            /// 在异步方法中:Await之前的执行还是调用的线程,Await之后的执行就是另一个线程了
            /// 即:异步方法中,Await之前还是当前线程的同步方法
            /// 
            /// </summary>
            /// <param name="ms"></param>
            /// <returns></returns>
            static async void DelayAsync(int ms)
            {
                Thread.Sleep(1000);
                Console.WriteLine("DelayAsync Before Await Thread ID:" + Thread.CurrentThread.ManagedThreadId);
                await DelayReturnTaskAsync(ms);
                Console.WriteLine("DelayAsync After Await Thread ID:" + Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(2000);
            }
    
            /// <summary>
            /// 异步代码里有异步代码
            /// </summary>
            /// <param name="ms"></param>
            /// <returns></returns>
            static async Task DelayReturnTaskAsync(int ms)
            {
                Thread.Sleep(1000);
                Console.WriteLine("DelayReturnTaskAsync Before Await Thread ID:" + Thread.CurrentThread.ManagedThreadId);
                await Task.Delay(ms);
                Console.WriteLine("DelayReturnTaskAsync After Await Thread ID:" + Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(2000);
            }
    
    
        }
    
    
  • 相关阅读:
    AngularJs+bootstrap搭载前台框架——准备工作
    Texygen文本生成,交大计算机系14级的朱耀明
    64个命令,每天一个linux命令目录, shutdown,tee,rcp,
    10个常用的ps命令总结,参数
    典型的知识库/链接数据/知识图谱项目
    十个Chatbot框架介绍
    Shell实现多级菜单系统安装维护脚本实例分享
    Java中判断字符串是否为数字的五种方法
    Shell中判断字符串是否为数字的6种方法分享
    shell产生随机数七种方法
  • 原文地址:https://www.cnblogs.com/swobble/p/11996486.html
Copyright © 2011-2022 走看看