I have this line of code:
t.ContinueWith(_ => form.Close(),
TaskScheduler.FromCurrentSynchronizationContext());
…about which the compiler has this to say:
Warning 2 Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the ‘await’ operator to the result of the call.
Now, this wasn’t code that I wrote, but I thought that it’s simply adding a continuation to the end of an existing task. I didn’t think it’s actually running the task (or the continuation). So surely this process of merely modifying the task is a synchronous operation? Why would I have to await it?
You don’t have to
awaitit, that’s why it is a warning, not an error. But, if you’re in anasyncmethod and you have a method that returns an awaitable object, most of the time, you shouldn’t ignore it.In normal synchronous code, you don’t have to do anything special to wait until a method you called completes, each method call always blocks. But with asynchronous methods, you actually have to
awaitthem if you want to wait until they complete. Also, if the asynchronous operation fails and throws an exception, you won’t know about it until youawaitthe result of the method (or get the exception from the result some other way, such as callingWait()if the awaitable is aTask).So, if you ignore a returned awaitable value in an
asyncmethod, it’s likely that you have a bug in your code, which is what the warning is trying to avoid.In your case,
ContinueWith()returns aTask, which can beawaited, so the compiler assumes that you shouldawaitit. But in this case, you don’t want to wait until the continuation completes andClose()most likely won’t throw an exception. So, in this case, the warning is a false positive, it does not actually indicate a problem in the code.