Is there any difference between waiting for the last asynchronous call and just returning it?

See the title of the question.

In other words, this method

async Task FrobnicateAsync() { ... }

is there any (possibly subtle) difference between

async Task FrobAndFrobnicateAsync()
{
    Frob();
    await FrobnicateAsync();
}

and

Task FrobAndFrobnicateAsync()
{
    Frob();
    return FrobnicateAsync();
}
+4
source share
2 answers

I have a blog post eliding async .

Since you have a non-trivial Frobup await, I recommend that you save asyncand await. The advantages of this approach are as follows:

  • async Frob , , . Frob , ; await .
  • async, Frob , FrobnicateAsync ( async); , FrobAndFrobnicateAsync. .

. ?

+2

, return FrobnicateAsync() - .

- , finally ( using) , return, await, finally t , async .

, async/await.

, ( ), , async/await, , using .

: , , :

Task FrobAndFrobnicateAsync()
{
    async Task Awaited(Task t) => await t;
    Frob();
    var task = FrobnicateAsync();
    // in .NET vFuture there will be a task.IsCompletedSuccessfully
    return task.State == TaskState.RanToCompletion ? task : Awaited(task);    
}

, .

+2

Source: https://habr.com/ru/post/1676349/


All Articles