http://msdn.microsoft.com/en-us/library/dd988458.aspx什么是TaskFactory.StartNew()中的“cancellationToken”用于?
UPD:
所以,让我们讨论一下这篇文章,那么:http://msdn.microsoft.com/en-us/library/dd997396.aspx
我已经改变了代码一点:
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;
Thread.Sleep(5000);
while (moreToDo)
{
// Poll on this property if you have to do
// other cleanup before throwing.
if (ct.IsCancellationRequested)
{
Console.WriteLine("exit");
// Clean up here, then...
ct.ThrowIfCancellationRequested();
}
}
}, tokenSource2.Token); // this parameter useless
Console.WriteLine("sleep");
Thread.Sleep(2000);
Console.WriteLine("cancel");
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();
}
UPD:嗯,这只改变了task.IsCanceled
,这是imho无用,因为我仍然应该手动实施全部。
请参阅[任务取消](http://msdn.microsoft.com/en-us/library/dd997396.aspx)。 – 2010-09-11 04:17:38
我见过它。 “},tokenSource2.Token)” - 这个参数没有改变。要么我们有或没有这个令牌传递 - 我们将得到一个异常,因为'ct'由闭包处理。 – zerkms 2010-09-11 04:27:38
太糟糕了,这个问题没有真正的答案,我也想知道这个论点的必要性......它现在看起来完全没有用处。 – 2011-09-15 21:30:35