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?
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?
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.
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.
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"