简体   繁体   中英

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();

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();

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 ).

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