简体   繁体   English

创建任务并“等待”它是否与同步运行某项任务或等待异步方法相同?

[英]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? 如果在UI线程上运行,以下代码块是否等效?

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

vs VS

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

Are the following code blocks equivalent if run on UI thread? 如果在UI线程上运行,以下代码块是否等效?

No they are not. 不,他们不是。 The first one will block the UI Thread / Message Pump , the second won't. 第一个将阻止UI线程 / 消息泵 ,第二个则不会。

The first is trying to run an async method Synchronously and would fail any sane code review (in all but the rarest of circumstances). 第一种是尝试同步运行async方法,并且将导致任何理智的代码审查失败(除了最罕见的情况)。 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 ). 我认为我无法详细介绍所有这些细节(很多细节),但是Stephen Cleary的文章中有很多对此细节进行了详细介绍( Async and await任务导论,第1部分:构造函数 Don在实现 中不 使用Task.Run ,并且没有线程 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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