Microsoft在 .NET 4 中给出了这个使用示例。CancellationToken
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();
}
}
但是,我的理解是,如果在一个线程上修改了变量,由于缓存,另一个线程可能无法获得修改后的值。并且由于在CancellationToken
主线程上取消了,线程如何Task
确保CancellationToken
它正在检查实际上是最新的?
为什么不能Task
读取令牌的缓存值?
注意:我提出这个问题的动机是想知道我是否需要CancellationToken
将实例变量设置为volatile
.