http://msdn.microsoft.com/en-us/library/dd988458.aspxÀ quoi sert "cancellationToken" dans TaskFactory.StartNew()?
UPD:
donc, nous allons discuter de cet article alors: http://msdn.microsoft.com/en-us/library/dd997396.aspx
J'ai changé ce code un peu:
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: Eh bien, cela change seulement task.IsCanceled
, qui est imho inutile, en raison de je devrais encore implémenter tout manuellement.
Voir [Annulation de tâche] (http://msdn.microsoft.com/fr-fr/library/dd997396.aspx). –
Je l'ai vu. "}, tokenSource2.Token)" - cet argument ne change rien. Soit nous avons ou non ce Token passé - nous obtiendrons une exception, car 'ct' est géré par la fermeture. – zerkms
Dommage qu'il n'y ait pas vraiment de réponse à cette question, je m'interroge aussi sur la nécessité de cet argument ... il semble totalement inutile pour le moment. –