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?
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.