简体   繁体   中英

Is using await on the UI thread the same as a blocking call?

Just reading and thinking aloud: if I used await on a call to a method from within the main UI thread, that would tantamount to being a blocking call, right, since there's no thread that called the UI thread?

For example:

int Main()
{
    // This would be a blocking call, right?
    await PrintTwoMillionTimes("Hello");

    Console.WriteLine("Phew! Done!");
}

No; the whole point of await is that it isn't a blocking call.
The compiler transforms the code after the await into a callback.

As long as the thing you're awaiting is well-behaved (meaning that it won't do its work synchronously), your UI will be fine.

No, absolutely not.

The point of await is that it doesn't block. Assuming the result of PrintTwoMillionTimes behaves sensibly, the async method will return immediately... but it will attach a continuation so that the rest of the method will execute (on the UI thread) when the result completes.

So assuming you've got a working example (currently your method declaration isn't async , and returns int , and you haven't got any return statements...) the flow is:

  • The async method starts
  • PrintTwoMillionTimes is called, which would start an asynchronous operation, returning something representing the operation (eg a Task )
  • The generated code would check whether the operation has already completed:
    • If it's already completed, execution continues
    • Otherwise, a continuation is attached to the task (or whatever is representing the operation) and the async method returns

If you're returning Task or Task<T> from the async method, the return value can be used to indicate when the async method itself has completed (ie after your Console.WriteLine has executed).

This is just a very brief description, of course. You should really read up on async/await in more detail. MSDN is a reasonable starting point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM