Water Cooler v2
Water Cooler v2

Reputation: 33850

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!");
}

Upvotes: 2

Views: 129

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500635

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 (e.g. 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 (i.e. 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.

Upvotes: 4

SLaks
SLaks

Reputation: 887451

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.

Upvotes: 5

Related Questions