Note that there are some explanatory texts on larger screens.

plurals
  1. POCancelling a Task is throwing an exception
    text
    copied!<p>From what I've read about Tasks, the following code should cancel the currently executing task without throwing an exception. I was under the impression that the whole point of task cancellation was to politely "ask" the task to stop without aborting threads.</p> <p>The output from the following program is:</p> <blockquote> <p>Dumping exception</p> <p>[OperationCanceledException]</p> <p>Cancelling and returning last calculated prime.</p> </blockquote> <p>I am trying to avoid any exceptions when cancelling. How can I accomplish this?</p> <pre><code>void Main() { var cancellationToken = new CancellationTokenSource(); var task = new Task&lt;int&gt;(() =&gt; { return CalculatePrime(cancellationToken.Token, 10000); }, cancellationToken.Token); try { task.Start(); Thread.Sleep(100); cancellationToken.Cancel(); task.Wait(cancellationToken.Token); } catch (Exception e) { Console.WriteLine("Dumping exception"); e.Dump(); } } int CalculatePrime(CancellationToken cancelToken, object digits) { int factor; int lastPrime = 0; int c = (int)digits; for (int num = 2; num &lt; c; num++) { bool isprime = true; factor = 0; if (cancelToken.IsCancellationRequested) { Console.WriteLine ("Cancelling and returning last calculated prime."); //cancelToken.ThrowIfCancellationRequested(); return lastPrime; } // see if num is evenly divisible for (int i = 2; i &lt;= num/2; i++) { if ((num % i) == 0) { // num is evenly divisible -- not prime isprime = false; factor = i; } } if (isprime) { lastPrime = num; } } return lastPrime; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload