How to cancel a Task?

Study a cancellation task using
CancellationToken
the button hung a handler that cancels the task and in the task check whether it is cancelled using the token.ThrowIfCancellationRequested();

When he reached the exception, the app crashes.
5a97e33a2aba1303339993.png
How to properly handle this exception?
June 7th 19 at 14:57
3 answers
June 7th 19 at 14:59
Solution
Once you throw an exception you have to catch.
See the examples or here https://blogs.msdn.microsoft.com/andrewarnottms/20...
In the case of await it worked at catching OperationCanceledException
thank you
5a97ea57ab005591456605.png

And if you make it through awaiter
try
{
 var awaiter = Go1Aync(cts.Token).Actual();
 awaiter.OnCompleted(()=>textBox1.Text = awaiter.GetResult());

}
 catch (OperationCanceledException)
{
 textBox1.Text = "operation canceled";

 }


the error is not caught. Don't know in what direction to dig? - cody_Stoltenberg commented on June 7th 19 at 15:02
Check the AggregateException object - Keira commented on June 7th 19 at 15:05
Unfortunately, it didn't help :) - cody_Stoltenberg commented on June 7th 19 at 15:08
June 7th 19 at 15:01
Solution
Process must not only OperationCancelledException, but also all other types of exceptions, using await:

try
{
await Go1Async(tcs.Token);
}
catch(Exception ex)
{
textBox1.Text = ex.Message;
}

At least when you run Go1Async(), if there is something to do with the network, we risk all sorts TimeoutException, WebException, just an IOException, and, in General, anything.

So, OperationCancelledException is just a special case of all possible variants of a failed operation.
June 7th 19 at 15:03

Find more questions by tags C#