Lets say I have something like this:
private CancellationTokenSource myToken;
public void MyMyMethod()
{
myToken = new CancellationTokenSource();
var task = Task.Factory.StartNew(() => DoIt(myToken.Token), myToken.Token);
Thread.Sleep(100);
myToken.Cancel();
}
public void MyOtherMethod()
{
myToken.Cancel();
}
private void DoIt(CancellationToken token)
{
token.ThrowIfCancellationRequested();
try
{
for (int i = 0; i < 1000000; i++)
{
Console.WriteLine(i);
}
}
catch (Exception ex)
{
string s = "";
}
}
If I call myToken.Cancel will it stop the task in the DoIt method abruptly or do I have to pass in the token to DoIt and call myToken.ThrowIfCancellationRequested() so that when the Cancel is called it will throw the exception and stop abruptly?
Can I not do this without passing in the token to the task method?
Or do I have to monitor token.IsCancellationRequested in the DoIt method?
By reading from here http://social.msdn.microsoft.com/Forums/da-DK/parallelextensions/thread/9f88132a-f8bd-4885-ab63-645d7b6c2127 it seems that the token is used to cancel the task BEFORE the task is “really” started, but after it has been queued.
You can even read it from Cancellation token in Task constructor: why?