Unicorn in C# (Not only Task and ValueTask can await) – Part 1

#csharp #dotnet #dotnetcore #software-engineering #net


David Shergilashvili

a year ago | 1 min read

C # has a lot of unicorn stuff hidden away, but many developers don’t know it, so they can’t make good use of these things. So today I will count the details hidden in the compiler.

Not only Task and ValueTask can await

When writing asynchronous code in C #, we often choose to include asynchronous code in a Task or ValueTask so that the caller can use wait to implement asynchronous calls.

not only Task and ValueTask can await. Task and ValueTask are scheduled by the thread pool, but why is async / await called a coroutine in C #?

Since what you are awaiting is not necessarily Task / ValueTask, in C # if your class contains a GetAwaiter () method and a bool IsCompleted property, and what GetAwaiter () returns contains a GetResult () method, the IsCompleted property is of type bool and implementing INotifyCompletion, you can await objects of that class.

Therefore, when encapsulating I / O operations, we can implement Awaiter ourselves, which is based on the underlying epoll / IOCP implementation, so that await will not create a thread and no thread scheduling will take place. take control directly. Upon completion of the I / O call, the OS notifies the user mode of the completion of the asynchronous call via CompletionPort (Windows), etc. At this time, the context is restored to continue executing the remaining logic, which is a real coroutine without a stack.

The asynchronous API related to I/O in .NET Core does this. During the I/O operation, there will not be any thread allocation waiting for the result. They are all coroutine operations: after the I/O operation starts. Give up control directly until the I/O operation is completed. And the reason why sometimes you find that the thread changes before and after await is just because the Task itself is scheduled.

The IAsyncAction/IAsyncOperation used in UWP development comes from the underlying package, which has nothing to do with Task but can be awaited, and if UWP is developed with C++/WinRT, the methods that return these interfaces can also be co_awaited.

#csharp #dotnet #dotnetcore #software-engineering #net


Created by

David Shergilashvili

Chapter Lead(Associate Partner) / R&D Developer at TBC Bank

I am an R&D Software Engineer, Certified DevOps Engineer Expert, Certified Azure Solutions Architect Expert, etc. With over 10 years of experience acquiring the requisite skill set, which I am very passionate about and strive to continually improve. I do not always meet all the requirements, but I am ready to learn and take the initiative. I always try to make the most of my opportunities and participate in interesting and complex projects(casinos, gambling, insurance, holding, government, banking), in which I embody all my knowledge and ideas.







Related Articles