Question about .Net and Async CTP Tasks

I am experimenting with Async CTP and love it quite a bit. However, I had a question from a guide explaining this. It says:

It is important to understand that asynchronous methods like (exemplary method specified in a white paper) do not run in their own thread.

If they do not start in their thread, how does asynchronous behavior work? How much context switches to the existing thread between the (say) user interface and the job created by the wait keyword?

+6
source share
2 answers

When you call the async method, it is initially synchronous. It does not even have the ability to be asynchronous until it reaches the wait.

For each pending expression, GetAwaiter() is called in the expected pending. The IsCompleted property is IsCompleted checked for awaiter. If the task is already completed, the method continues synchronously.

Otherwise, the OnCompleted method OnCompleted called in awaiter to add a continuation to it, which then returns when the task completes. The async method itself returns to the caller the first time it accesses a pending expression that is not yet complete.

The exact nature of the streaming depends on the student, but in async CTP for Task<T> , TaskAwaiter will use the current task scheduler to schedule a continuation. For WinForms / Silverlight / WPF, this means that if you run the asynchronous stream method in the user interface thread, it continues in the user interface thread. Otherwise (for example, if you are already using a stream stream or using it from a console application), the continuation will be performed in the stream stream. Of course, you can change the current task scheduler if you want.

Similar to other expectations, you do not need to plan a continuation using TaskScheduler.Current . For example, my coroutine continuations basically keep a continuation queue for execution and keep going until they go. My ComeFrom sequels are getting weirder :)

For more on how the async function works under the hood, read my Eduasync blog post

+5
source

The idea of ​​the async method is that it does not require a thread to start, it just makes a call and a connection terminating the asynchronous workflow in a linear fashion. That is, if you use the async method to read from a file, it synchronously calls the initial part of the read file and then pauses execution (i.e., refuses the current thread to perform other operations) until the OS-level operation completes and causes completion to complete, which does not pauses the remainder of your asynchronous method (at least until the next wait).

+1
source

Source: https://habr.com/ru/post/889725/


All Articles