Reputation: 785
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?
Upvotes: 7
Views: 218
Reputation: 457302
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.
Upvotes: 2
Reputation: 34421
If the only await is as the last statement (and you are awaiting a task, as opposed to some other awaitable object), you can as well skip it and just return the task. It's easy to add the async modifier, should it be needed in the future.
Upvotes: 0