Microsoft gives this example of CancellationToken
use in .NET 4.
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main()
{
var tokenSource2 = new CancellationTokenSource();
CancellationToken ct = tokenSource2.Token;
var task = Task.Factory.StartNew(() =>
{
// Were we already canceled?
ct.ThrowIfCancellationRequested();
bool moreToDo = true;
while (moreToDo)
{
// Poll on this property if you have to do
// other cleanup before throwing.
if (ct.IsCancellationRequested)
{
// Clean up here, then...
ct.ThrowIfCancellationRequested();
}
}
}, tokenSource2.Token); // Pass same token to StartNew.
tokenSource2.Cancel();
// Just continue on this thread, or Wait/WaitAll with try-catch:
try
{
task.Wait();
}
catch (AggregateException e)
{
foreach (var v in e.InnerExceptions)
Console.WriteLine(e.Message + " " + v.Message);
}
Console.ReadKey();
}
}
However, my understanding is that if a variable is modified on one thread, another thread might not get the modified value, due to caching. And since the CancellationToken
is cancelled on the main thread, how is the Task
thread assured that the CancellationToken
it is checking is actually up-to-date?
Why isn't it possible for the Task
to be reading a cached value of the token?
Note: My motivation in asking this arises from wondering whether I need my CancellationToken
instance variables to be volatile
.