有沒有辦法將取消標記綁定到由另一個取消標記控制的任務的子集?在本例中,我創建了兩個cancellationTokenSource .. 。註冊一個對另一個的取消功能...這種方式,如果我取消加載的圖像...它只取消這些任務...但如果我取消所有...它取消所有任務...是有更好的方法來做到這一點? (這種方式似乎很混亂......例如何時取消註冊)CancellationToken影響由另一個CancellationToken控制的任務的子集的好方法
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)