What is the difference between async Task and Task [duplicate]

耗尽温柔 提交于 2019-12-20 06:47:24

问题


For example, what is the difference between this code:

public async Task DoSomething(int aqq)
{
    await DoAnotherThingAsync(aqq);
}

and this one:

public Task DoSomething(int aqq)
{
    DoAnotherThingAsync(aqq);
}

Are they both correct?


回答1:


Both signatures are correct, if used properly.

async Task allows you to use await keyword inside your method. The first example is totally OK.

The second example missing return statement:

public Task DoSomething(int aqq)
{
   return DoAnotherThingAsync(aqq);
}

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.




回答2:


In your sample, no. Your second method breaks the task chain, which is entirely wrong and can cause hard to find bugs and weird behaviour overall.

You need to return the task if you're not using async (which handles the return for you automagically).

There's also some subtle differences that are important when debugging and a few other gotchas, but that's quite a broad topic :) Until you understand the issue perfectly, just use async and await - they are the highest level tool available in C# at this point.




回答3:


Yeah, they both correct, but second is better.

Async keyword is just a syntaxic sugar that allow us to write linear code instead of strange style of manual handling tasks.

First variant is compiled into state machine and it results that it takes a bit more time than second variant. You even can rewrite first variant to return Task.Run(() => DoAnotherThingAsync(aqq).Result) to get idea where is the difference. Note: this is just an idea, instead rewriting of first method is more complex. I just want to show you that your variants not similar.

You can read more about how async works in the article "Async Await and the Generated StateMachine"



来源:https://stackoverflow.com/questions/38121262/what-is-the-difference-between-async-task-and-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!