lahsrah
lahsrah

Reputation: 9173

Is creating a task and "Waiting" it the same as running something synchronously or awaiting an async method?

Are the following code blocks equivalent if run on UI thread?

var task = Task.Run(async () => { await DoSomething(); });
task.Wait();

vs

await DoSomething(); //Or DoSomething.Wait();

Upvotes: 0

Views: 61

Answers (2)

Erik Philips
Erik Philips

Reputation: 54618

Is creating a task and “Waiting” it the same as running something synchronously?

The following code is; creating a task, creating a new thread, and running code on the new thread.

var task = Task.Run(async () => { await DoSomething(); });

It's important to know that all of that happens.

Assuming the signature:

async Task DoSomething()

All of the statements below are fundamentally different:

Task.Run(async () => { await DoSomething(); });
await DoSomething(); 
DoSomething().Wait();

I don't think I could go into detail about all of these (it's a lot of detail) but Stephen Cleary's has quite a number of posts that go into this detail (Async and await, A Tour of Task, Part 1: Constructors Don't Use Task.Run in the Implementation, and There is no thread).

Upvotes: 1

TheGeneral
TheGeneral

Reputation: 81493

Are the following code blocks equivalent if run on UI thread?

No they are not. The first one will block the UI Thread/Message Pump, the second won’t.

The first is trying to run an async method Synchronously and would fail any sane code review (in all but the rarest of circumstances). The first example should be changed to be the second example IMHO

Is creating a task and “Waiting” it the same as running something synchronously?

If you define Synchronous code as "A bunch of statements in sequence; so each statement in your code is executed one after the other, and there is no code before the wait". Then you can make this claim.

However, if you do something like this, then no

var task = Task.Run(SomeAwesomeTask);

// lots more code here

task.Wait();

Upvotes: 3

Related Questions