This is a linqpad example of two ways of executing a method asynchronously after a short delay. Both examples appear to do exactly the same thing. I would normally implement the first version (using Task.Delay.ContinueWith), but I've seen the second implementation used (async await) too. Is there any difference at all between these two implementations? Working Linqpad example of this scenario:
void Main()
{
// Using Task.Delay.ContinueWith...
Task.Delay(1000).ContinueWith(t => DoSomething());
// ... vs async await. Note that I'm not awaiting the task here
DoSomethingAsync();
}
public void DoSomething()
{
"Doing Something...".Dump();
}
public async Task DoSomethingAsync()
{
await Task.Delay(1000);
"Doing Something...".Dump();
}
After reading this blog post https://blogs.msdn.microsoft.com/pfxteam/2012/03/24/should-i-expose-asynchronous-wrappers-for-synchronous-methods/ I assumed the first implementation was the 'correct' one because the 'DoSomethingAsync()' is really only offloading the method to the threadpool and the blog post states:
"Asynchronous methods should not be exposed purely for the purpose of offloading: such benefits can easily be achieved by the consumer of synchronous methods using functionality specifically geared towards working with synchronous methods asynchronously, e.g. Task.Run."
However, this answer on StackOverflow suggests the second solution:
Is there any actual difference between the two implementations? If the 'async await' implementation is also valid (or more correct even), what should be done with the returned Task? I don't really want to wait for it, this is a fire-and-forget operation, but I also want to handle any exceptions that might be thrown.
In the first implementation I know I could handle the exception by using a ContinueWith, OnlyOnFaulted.