Asynchronous design - which one is better?

I became interested in asynchronous programming, I should always use the following template:

public async Task<int> MyMethodAsync()
{
    return await SomeOtherMethodAsync();
}

or it is safe and gives no flaw, simplify this code so that:

public Task<int> MyMethodAsync()
{
    return SomeOtherMethodAsync();
}

I started reading over the Internet and can’t find the answer; all asynchronous programming mentions only the first template.

UPDATE 1

Based on some answer, in the trivial method the second is correct. But if I continue and write the method as follows, this still applies to the above code, just to show what's inside the method SomeOtherMethodAsync:

public async Task<int> SomeOtherMethodAsync()
{
    var result1 = await LongRunningThirdMethod();
    var result2 = await LongRunningForthMethod();

    return result1 + result2;
}

and change my second example to:

public Task<int> MyMethodAsync()
{
    SomeSyncMethod();
    SomeOtherSyncCode();

    return SomeOtherMethodAsync();
}
+4
source share
2 answers

.

async/await , . Async, .

, , async, .

1

. /async, , , , . , async/await.

, .

public async Task<int> SomeOtherMethodAsync()
{
    var resultTask1 = LongRunningThirdMethod();
    var resultTask2 = LongRunningForthMethod();

    await Task.WhenAll(resultTask1, resultTask2);

    return resultTask1.Result + resultTask2.Result;
}

:

public async Task<int> SomeOtherMethodAsync()
{
    var resultTask1 = LongRunningThirdMethod();
    var resultTask2 = LongRunningForthMethod();

    return await resultTask1 + await resultTask2;
}

. , . , , . , , ... ..

+2

, . , , , Task, .

( 1) . , , Task.WhenAll:

public async Task<int> SomeOtherMethodAsync()
{
    int[] results = await Task.WhenAll(LongRunningThirdMethod(), LongRunningForthMethod());
    return results.Sum();
}

, . , .

+1

All Articles