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