locked
cancelling a task, two questions

    Question

  • hello

    this is my sample code

     Task<long> task = Task.Run(() =>
    			{
    				long total = 0;
    
    				for (int i = 0; i < 999999999; i++)
    				{
    					token.ThrowIfCancellationRequested(); 
    					total += i;
    				}
    				return total;
    			}
    			, token 
    			);
    1. What happen if I forgive to pass the cancellation token (token) into Run function? I can't see any behavior difference
    2. Instead of running ThrowIfCancellationRequested, why not just doing break after checking a cancellation has been requested with token.IsCancellationRequested

      thank you


    Thank you!

    Wednesday, November 28, 2012 9:28 AM

Answers

  • #1 There will be two primary differences.  First, the Task will eventually start executing regardless of whether cancellation was requested before the thread pool got around to processing it; if you pass the token as a parameter to Run, the token will be monitored and the Task can transition directly to Canceled rather than first starting to execute. Second, the Task will end in the Faulted state instead of in the Canceled state. 

    #2 The Task would then end as RanToCompletion rather than as Canceled (or, per #1, as Faulted if you don't pass the token as a parameter).  That means that anyone monitoring the outcome will think the Task completed all of the work it was meant to, e.g. your Task's result will be incorrect (because you only completed part of the work), but there will be no indication of that because the task will appear to have completed successfully.

    Wednesday, November 28, 2012 3:41 PM
    Moderator