有没有办法将取消令牌绑定到由另一个取消令牌控制的任务子集?......在这个例子中,我创建了两个cancellationTokenSource......并将一个注册到另一个的Cancel函数......如果我这样取消图像的加载...它只会取消那些任务...但是如果我取消所有...它会取消所有任务...有没有更好的方法来做到这一点?(这种方式看起来很乱......例如何时取消注册)
CancellationTokenSource CancelAllSource = new CancellationTokenSource();
for (int i = 0; i < 20; i++)
Task.Factory.StartNew(() => { LoadUrl(i, CancelAllSource.Token); });
CancellationTokenSource CancelImageLoadsSource = new CancellationTokenSource();
// this would connect the cancel all token to the cancel image loads token
CancelAllSource.Token.Register(CancelImageLoadsSource.Cancel, false);
for (int i = 0; i < 10; i++)
Task.Factory.StartNew(() => { LoadImage(i, CancelImageLoadsSource.Token); });
...
CancelImageLoadsSource.Cancel(); // would cancel only the LoadImage tasks
// or
CancelAllSource.Cancel(); // would cancel all tasks (including the LoadImage tasks)