What happens to an `awaiting` thread in C# Async CTP?

前端 未结 2 1066
醉酒成梦
醉酒成梦 2020-12-24 07:40

I\'ve been reading about the new async await keyword and it sounds awesome, but there is one key question I haven\'t been able to find the answer for in any of

2条回答
  •  醉酒成梦
    2020-12-24 07:45

    It depends on the behavior of Awaitable.

    It has the option to run synchronous, i.e. it runs on the thread and returns control back to the awaiter on the same thread.

    If it chooses to run asynchronously, the awaiter will be called back on the thread that the awaitable schedules the callback on. In the meantime the calling thread is released, since there is awaitable started it's asynchronous work and exited and the awaiter has had its continuation attached to callback of the awaitable.

    As to your second question, the async keyword is not about whether the method is called asynchronously or not, but whether the body of that method wants to call async code inline itself.

    I.e. any method returning Task or Task can be called asynchronously (awaited or with continuewith), but by also marking it with async, that method can now use the await keyword in its body and when it returns it doesn't return a Task, but simply T, since the entire body will be rewritten into a state machine that the Task executes.

    Let's say you have method

    public async Task DoSomething() {
    }
    

    when you call it from the UI thread you get back a task. At this point, you can block on the Task with .Wait() or .Result which runs the the async method on its TaskScheduler or block with .RunSynchronously() which will run it on the UI thread. Of course any await that occurs inside DoSomething is basically another continuation, so it might end up running part of the code on a TaskScheduler thread. But in the end the UI thread is blocked until completion, just like a regular synchronous method.

    Or you can schedule a continuation with .ContinueWith() which will create an action that gets called by the TaskScheduler when the Task completes. This will immediately return control to the current code which continues to do whatever it was doing on the UI thread. The continuation doesn't capture the callstack, it's simply an Action, so it merely captures any variables it access from its outer scope.

提交回复
热议问题