async/await 的使用

async :
html

使用 async 修饰符可将方法、lambda 表达式匿名方法指定为异步。 若是对方法或表达式使用此修饰符,则其称为异步方法express

await:编程

await 运算符应用于异步方法中的任务,在方法的执行中插入挂起点,直到所等待的任务完成,返回线程池任务表示正在进行的工做。多线程

 

 

 区别:异步

     同步方法:一个程序调用某个同步方法,等到其执行完成以后才进行下一步操做。这也是默认的形式。
     异步方法:一个程序调用某个异步方法(建立线程 【线程池】),取处理完成以前就返回该方法,并继续往下执行其余代码。

 

 

 执行流程:async

异步用例:ide

只有拥有async才能在其内部使用await关键字。异步方法能够具备Task、Task<>或void的返回类型;异步编程

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("主线程测试开始..");
            AsyncMethod();
            Thread.Sleep(1000);
            Console.WriteLine("主线程测试结束..");
            Console.ReadLine();
        }

        static async void AsyncMethod()
        {
            Console.WriteLine("开始异步代码");
            var result = await MyMethod();//var result = MyMethod().Result
            Console.WriteLine("异步代码执行完毕");
        }

        static async Task<int> MyMethod()
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("异步执行" + i.ToString() + "..");
                await Task.Delay(1000); //模拟耗时操做
            }
            return 0;
        }
    }

 

Thread多线程异步编程例子:测试

class Program { static void Main(string[] args) { Console.WriteLine("主线程测试开始.."); Thread th = new Thread(ThMethod); th.Start(); Thread.Sleep(1000); Console.WriteLine("主线程测试结束.."); Console.ReadLine(); } static void ThMethod() { Console.WriteLine("异步执行开始"); for (int i = 0; i < 5; i++) { Console.WriteLine("异步执行" + i.ToString() + ".."); Thread.Sleep(1000); } Console.WriteLine("异步执行完成"); } }


 

 

 

参考:   http://www.javashuo.com/article/p-pxxfsemu-q.html   //线程池传送门ui

    http://www.javashuo.com/article/p-tqcehmav-w.html

    http://www.javashuo.com/article/p-rivobvpq-bz.html

    https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/async/

    http://www.javashuo.com/article/p-glgzatop-kc.html