Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we always need to use async keyword?

Let's consider this code:

public async Task TheBestMethodEver1()
{
// code skipped
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
  // code skipped
});

}

public Task TheBestMethodEver2()
{
  // code skipped
  return Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
  {
    // code skipped
  }).AsTask();
}

Any of these methods can be called like:

await TheBestMethodEverX();

What is the difference between these two methods and why should I use the first one usually?

like image 519
A-student Avatar asked Oct 23 '12 08:10

A-student


1 Answers

What is the difference between these two methods and why should i use the first one usually?

The first one has a compiler-generated state machine and creates additional garbage on the heap. Therefore the second one is preferred.

For more information, watch the classic Zen of Async video.

like image 53
Stephen Cleary Avatar answered Nov 09 '22 23:11

Stephen Cleary