Should I always use the async keyword?

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 as:

 await TheBestMethodEverX(); 

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

+7
source share
2 answers

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

The first has a machine generated by the compiler and creates additional garbage on the heap. Therefore, second is preferable.

Watch the classic Zen of Async video for more information.

+2
source

If the only expectation is the last statement (and you are expecting a task, not some other expected object), you can also skip it and simply return the task. It’s easy to add the async modifier if you need it in the future.

0
source

All Articles