Why am I getting a compiler warning when using ContinueWith?

I have this line of code:

t.ContinueWith(_ => form.Close(), TaskScheduler.FromCurrentSynchronizationContext()); 

... of which the compiler says the following:

Warning 2 Since this call is not expected, execution of the current method continues until the call ends. Consider applying a wait statement to a call result.

Now it was not the code that I wrote, but I thought that it just adds a continuation to the end of the existing task. I did not think that he was really doing the task (or continuation). Is this process of simply changing a task a synchronous operation? Why do I need to await him?

+7
source share
1 answer

Why do I need to await him?

You do not need to await it, so this is a warning, not an error. But if you use the async method, and you have a method that returns the expected object, most of the time you should not ignore it.

In normal synchronous code, you do not need to do anything special to wait until the method you call completes, each method call is always blocked. But with asynchronous methods, you really need to await them if you want to wait until they run out. In addition, if the asynchronous operation fails and throws an exception, you will not know about it until you get the await method result (or get an exception from the result in some other way, for example, calling Wait() if the expected one is Task ).

So, if you ignore the returned expected value in the async method, you probably have an error in the code, which warns.

In your case, ContinueWith() returns a Task , which may be await ed, so the compiler assumes that you should await it. But in this case, you do not want to wait for the continuation to complete, and Close() will most likely not throw an exception. Thus, in this case, the warning is false positive, it does not actually indicate a problem in the code.

+8
source

All Articles