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?
Why would I have to
await
it?
You don't have to await
it, that's why it is a warning, not an error. But, if you're in an async
method 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 await
them 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 you await
the result of the method (or get the exception from the result some other way, such as calling Wait()
if the awaitable is a Task
).
So, if you ignore a returned awaitable value in an async
method, 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 a Task
, which can be await
ed, so the compiler assumes that you should await
it. But in this case, you don't want to wait until the continuation completes and Close()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With