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?