C # asynchronous programming is enough to see this

With the popularity of .NET Core, I believe you are now more or less code will be used asyncas well await, right! After all, it has become the standard. So why do we use asyncand awaitwhat? In fact, this is a syntactic sugar provided us with the Microsoft team, so we do not have 996 can easily write asynchronous code, not too magical place. So, the question is, what is the asynchronous? Asynchronous in the end is what kind of a process it?

Speaking from a story

Before we start talking about asynchronous start a life story talking about it. Saying December 15, 2019 Sunday, this day I wish there was a small program ape on this day there were no overtime, chooses to stay home to rest, then he habitually with Microsoft To Dolists of things to do at this day, as shown below:

image-20191215143106499

On this day I wish this program little ape plans to nine in the morning to get up to take a bath, and then eat breakfast, laundry, share an article on C#异步related articles, plus home from work at night ~ ~ Yes, this hard to force the rest of the time they have to work, or at Zhou able to fulfill the task is likely to be being criticized.

This time the program may wish to select a small ape, 1. get a bath, 2 breakfast, 3 laundry, 4. write articles 5. Then the ball would hit the "Remote write code." This process has a strict order of execution, the process can be seen as a process of synchronization. As shown below:

image-20191215144358900

Of course, this program ape Kohafuri has adopted another way to be: first clothes after getting down for machine washable, and then began to take a shower, then eat, write articles for a while, and then wash the clothes, etc. hanging clothes to keep coming back to write good articles, and finally write the code in the evening when remote. In this process, the program ape to go take a shower while washing clothes, eating will write articles, this process is an asynchronous process.

This story may be inappropriate analogy, but everyone will look forward to it, summarize it synchronous with asynchronous:

  1. Synchronization: You can assume that the program is related to the instructions executed in the order you write the code used.
  2. Asynchronous: You can return all the instructions in advance has not been completed when (as in the above washing process did not return to complete the implementation of a bath), after that task execution until the process is finished waiting, in this order from the earlier method also that place did not continue executing the run down (such as: dry after a good wash clothes well, continue to write articles).

下面我们结合伪代码来进行更加详细的讲解吧。

伪代码实例讲解

这一节我们就用伪代码来分别实现下同步过程及异步过程吧。

同步过程

下面我们用伪代码来实现上述故事中的过程吧。

 static void Main(string[] args)
        {
            Console.WriteLine("Main异步演示开始~~~~~");
            Stopwatch stopwatch = Stopwatch.StartNew();
            Bash();//洗澡
            BreakFast();//吃早餐
            WashClothes();//洗衣服
            WriteArticle();//写文章
            WritingCode();//写代码
            Console.WriteLine("Main异步演示结束~~~~~共用时{0}秒!", stopwatch.ElapsedMilliseconds/1000);
            Console.ReadKey();
        }

        private static void Bash()
        {
            Console.WriteLine("洗澡开始~~~~~");
            Thread.Sleep(1*1000);//模拟过程
            Console.WriteLine("洗澡结束~~~~~");
        }

        private static void BreakFast()
        {
            Console.WriteLine("吃早餐开始~~~~~");
            Thread.Sleep(1 * 1000);//模拟过程
            Console.WriteLine("吃早餐结束~~~~~");
        }

        private static void WashClothes()
        {
            Console.WriteLine("洗衣服开始~~~~~");
            Thread.Sleep(6 * 1000);//模拟过程
            Console.WriteLine("洗衣服结束~~~~~");

        }

        private static void WriteArticle()
        {
            Console.WriteLine("写文章开始~~~~~");
            Thread.Sleep(20 * 1000);//模拟过程
            Console.WriteLine("写文章结束~~~~~");
        }

        private static void WritingCode()
        {
            Console.WriteLine("写代码开始~~~~~");
            Thread.Sleep(12 * 1000);//模拟过程
            Console.WriteLine("写代码结束~~~~~");
        }

上面的代码没什么难的,写完代码后我们直接dotnet run一下代码,如下图所示:

image-20191215153032564

我们可以看到这个代码的执行过程是严格按照我们编码的顺序执行的,即同步运行的代码。这里用时共40秒!

异步过程

我们只需要稍微改造下使得代码异步执行再来看下效果吧!伪代码如下:

 static async Task Main(string[] args)
        {
            Console.WriteLine("Main异步演示开始~~~~~");
            Stopwatch stopwatch = Stopwatch.StartNew();
            List<Task> tasks = new List<Task>
            {
                Bash(),//洗澡
            };
            tasks.Add(BreakFast());//吃早餐
            tasks.Add(WashClothes());//洗衣服
            tasks.Add(WriteArticle());//写文章
            tasks.Add(WritingCode());//写代码
            await Task.WhenAll(tasks);
            Console.WriteLine("Main异步演示结束~~~~~共用时{0}秒!", stopwatch.ElapsedMilliseconds/1000);
            Console.ReadKey();
        }

        private static async Task Bash()
        {
            Console.WriteLine("洗澡开始~~~~~");
            await Task.Delay(1*1000);//模拟过程
            Console.WriteLine("洗澡结束~~~~~");
        }

        private static async Task BreakFast()
        {
            Console.WriteLine("吃早餐开始~~~~~");
            await Task.Delay(1 * 1000);//模拟过程
            Console.WriteLine("吃早餐结束~~~~~");
        }

        private static async Task WashClothes()
        {
            Console.WriteLine("洗衣服开始~~~~~");
            await Task.Delay(6 * 1000);//模拟过程
            Console.WriteLine("洗衣服结束~~~~~");

        }

        private static async Task WriteArticle()
        {
            Console.WriteLine("写文章开始~~~~~");
            await Task.Delay(20 * 1000);//模拟过程
            Console.WriteLine("写文章结束~~~~~");
        }

        private static async Task WritingCode()
        {
            Console.WriteLine("写代码开始~~~~~");
            await Task.Delay(12 * 1000);//模拟过程
            Console.WriteLine("写代码结束~~~~~");
        }

然后我们再直接dotnet run一下代码,如下图所示:

image-20191215154823294

我们可以看到这个代码的执行过程中遇到await后就会返回执行了,待await的代码执行完毕后才继续执行接下来的代码的!为了避免有的读者看不懂,我简单分析其中一个方法的执行过程吧。具体的还需要你自己把异步代码拷贝下来,多打几个断点,然后把等待时间*100(时间长点方便我们查看断点的进入顺序,否则时间短,还没来得及进断点可能代码已经执行完了)看看断点的进入步骤吧!

image-20191215160556885

我也只列了一部分,具体的你们自行打断点看下吧。

异步原理解析

通过上面的伪代码分析相信你已经对异步有所了解了。接下来我们就来看看系统到底是怎么实现出这样的效果的。下面只是简单地进行下表述,如果不正确的欢迎大家指正。

编译器在处理异步方法的时候,会构建一种机制,该机制可以启动await 语句所要等候的那项异步任务,并使得程序在该工作完成之后,能够用某个线程继续执行await语句后面的那些代码。这个await语句正是关键所在。编译器会构建相应的数据结构,并把await之后的指令表示成delegate,使得程序在处理完那项异步任务之后,能够继续执行下面的那些指令。编译器会把当前方法中的每一个局部变量的值都保存在这个数据结构中,并根据await语句所要等候的任务来配置相应的逻辑,让程序能够在该任务完成之后指派某个线程,从await语句的下一条指令开始继续执行。实际上,这相当于编译器生成了一个delegate,用以表示await语句之后的那些代码,并写入了相应的状态信息,用以确保await语句所等候的那项任务执行完毕以后这个delegate能够正确的得到调用。

这使得该方法看上去好像是从早前暂停的地方继续往下执行了,也就是所,系统会把状态恢复到早前暂停的样式,并且直接把程序中的某个线程放到适当的语句上,令其能够继续向下运行。

这个过程实际上是由SynchronizationContext类来实现的,该类用来保证异步方法能够在它所等候的任务执行完毕时,从早前停下来的地方继续往下运行,并确保该方法此时所处的环境与上下文能够与当初的情况一样。

总结

Through the above we can know about through asyncthe awaitwritten keyword asynchronous method is not too magical place. But the compiler generates a lot of code for this method, this method makes the call to the calling party without waiting for the completion of the process, you can continue down the implementation, and ensure that the method is waiting for that task occurs during execution the error can be properly rewarded. The advantage is that, if the asynchronous method execution when it will wait to await the statement that task has not been completed, then the progress in the implementation of the method will pause there until after that task is completed, before returning to continue down the implementation.

Hopefully this article for your help, of course, light Understanding the asynchronous useless, but also to be able to write asynchronous code efficient job Oh, then I will take the time to talk about some suggestions asynchronous development. Of course, I've written related articles, you can look ahead. At the same time welcome to join the .net core thousand people exchange group 637326624` exchange. Of course I will not tell you, concerned about the public number will be the first time we receive articles pushed.

Long time no write articles, after more than rusty, we will forward it out!

reference

"More Effective C #" Machinery Industry Press

I wish the music according to their own understanding

Guess you like

Origin www.cnblogs.com/yilezhu/p/12045018.html