ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

What the async keyword actually does

2022-07-04 10:05:08  阅读:195  来源: 互联网

标签:machine What Task will state does async method


What the async keyword actually does

When it comes to curiousity about inner workings of C# keywords or construct, async and await are at the top of my list by a mile. The amount of complicated intrinsics packed into two simple keywords which magically improve performance by a big margin is absolutely astounding.

However, one of the things I picked up over the years was a saying along the lines of “You should always know what’s going on one or two layers below the abstraction you’re working on.

Therefore, in this post, I’d like to dissect a bit what the async keyword actually does to your code, and potentially also teach you some pitfalls and tricks to use.

The async keyword

In short, the async method allows your method to make use of the async/await paradigm. When using this keyword, your method is required to either return void, Task, Task<T>, a task-like type, or one of the new kids on the block, like ValueTask, IAsyncEnumerable<T> etc.

Also, the await keyword can only be used within async methods.

However, the most significant piece of work connected to the async keyword is the state machine the compiler makes out of it.

The async state machine

Let’s start with the following code:

async Task Main()
{
    var httpClient = new HttpClient();
    var result = await httpClient.GetStringAsync("https://medium.com");
    Console.WriteLine(result);
}

This is a super basic async method. It creates an HttpClient, performs an asynchronous GET HTTP request, and writes the result to the Console.

However, let’s now take a look what the compiler creates out of this method:

Now, that is arguably quite a different beast. This is the state machine the compiler generates for every method / lambda with the async keyword. It essentially turned the method into a class.

Let’s go through the interesting parts outside of the boilerplate attributes and explicit interface implementations.

The transformed Main() method

The transformed Main() method is not too exciting, and fairly straightforward:

Here we create an instance of the state machine class. In addition to that it

  • Creates an AsyncTaskMethodBuilder. This will later be used to glue callbacks to the state machine

Also, we return the inner Task here.

The <Main>d__0 class

Let’s take a quick look at the generated class itself. It implements the IAsyncStateMachine interface, and this is exactly what this class represents - a state machine.

This causes various things to happen:

  • A state field is introduced to keep track of the current state

The MoveNext() method

This is the heart of the state machine, and this is also where the magic happens:

If you take a closer look at this method, you will see that this essentially represents the initial async method, but in a very split up fashion. Note that this split also happens exactly around the places the await keyword is placed.

Let’s step through:

  1. On the first execution, the state is set to -1, as it was initialized in the Main() method. This means, execution will step into the first if clause, and initialize the HttpClient.

If at any point in the state machine’s execution an Exception would have been raised, you can see that everything takes places in a try/catch block, and potential Exceptions are stored on the Task of our method. This exception will be raised, as soon as an attempt is made to grab the Result of the Task, which, as we just saw, happens regularily within state machines. Note that this is also the reason why using async void is considered dangerous. If there is no Task to stick Exceptions on, then it would just bubble up and potentially crash your application. However, even with a Task you are not guaranteed to be safe. If no one ever tries to access the result of your Task, then the CLR will throw an UnobservedTaskException when attempting to collect the memory at some point in time.

The state machine can grow increasingly complex, with more await’s, the compiler will change the basic if usages to more complex switch statements accordingly as well. However, even in a very complex operation, the basic principle will always stay the same, and you can stick together layers on layers of these state machines, the mechanism will always be the same.

Anyways, that’s it! With a bit of reading through the code, it is not too hard to roughly understand what is going on. Of course, I skipped through some of the internals even deeper, but as I mentioned, it’s always worth it to know the abstraction one or two layer below your code, but that doesn’t mean you need to know everything in detail. Knowledge of how it roughly works is very valuable already.

 

 

标签:machine,What,Task,will,state,does,async,method
来源: https://www.cnblogs.com/chucklu/p/16441921.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有