4

There are two methods

public async Task T1()
{
    await Task.Run(() => /*do something here*/);
}

public Task T2()
{
    return Task.Run(() => /*do something here*/);
}

Is there any difference between them?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Vitalii
  • 10,091
  • 18
  • 83
  • 151
  • At the call site (e.g. from the perspective of someone calling these methods), no there is no difference. – spender Nov 26 '15 at 09:18
  • However, awaiting `Task.Run` is usually associated with the misguided practice of using `Task.Run` in order to run "synchronous code asynchronously". – spender Nov 26 '15 at 09:21
  • If you check the types, you can found out that T1 actually returns a `Task`, T2 returns a non-generic `Task`. – Dennis_E Nov 26 '15 at 09:39
  • first method just adds some overhead. running it in async mode is not necessary. – M.kazem Akhgary Nov 26 '15 at 10:01

1 Answers1

0

I believe the first variant will wait for the task to finish (not by blocking the thread, but by signing the rest of the method up to be executed when the task is done, in the Continuation Passing Style). The second option won't. You've started and returned a task, but your calling thread will just carry on unless it calls .Wait() or something.

The async/await stuff is just syntactic sugar around re-writing methods using Task and the continuation passing style, though the result is typically complex enough that you wouldn't do it by hand.

Neil Barnwell
  • 41,080
  • 29
  • 148
  • 220