异步任务和任务之间有什么区别 [英] What is the difference between async Task and Task
问题描述
例如,这段代码有什么区别:
For example, what is the difference between this code:
public async Task DoSomething(int aqq)
{
await DoAnotherThingAsync(aqq);
}
和这个:
public Task DoSomething(int aqq)
{
DoAnotherThingAsync(aqq);
}
它们都正确吗?
推荐答案
如果使用正确,两个签名都是正确的.
Both signatures are correct, if used properly.
async Task
允许您在方法内部使用await关键字.第一个例子完全可以.
async Task
allows you to use await keyword inside your method. The first example is totally OK.
第二个示例缺少return语句:
The second example missing return statement:
public Task DoSomething(int aqq)
{
return DoAnotherThingAsync(aqq);
}
使用第二个签名,您不能使用await关键字,但是您仍然可以返回从其他地方获得的某些任务,例如Task.FromResult(true);
Going with second signature you cannot use await keyword, but still you can return some task, that you got from somwhere else, for example, Task.FromResult(true);
为您提供另一个区别,请考虑以下示例:
To give you another difference consider the example:
public async Task DoSomething1(int aqq)
{
await DoAnotherThingAsync(aqq); //blocks here and wait DoAnotherThingAsync to respond
SomethingElse();
}
public Task DoSomething2(int aqq)
{
var task = DoAnotherThingAsync(aqq); //keep going here, not waiting for anything
SomethingElse();
return task;
}
public async Task DoAnotherThingAsync(int aqq)
{
await Task.Delay(100);
}
public void SomethingElse()
{
//do something
}
如果您使用异步/等待,则实际上是在等待任务完成.返回任务并不等待任务完成.
If you are using async/await you are actually waiting the task to complete. Returning a task doesn't wait for the task to be completed.
这篇关于异步任务和任务之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!