1 回答

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
CancellationToken如果你想單獨(dú)取消它們,你需要為你開始的每個(gè)任務(wù)傳遞一個(gè):
static async Task Main(string[] args)
{
var cancellationSources = Enumerable.Range(0, 3)
.Select(_ => new CancellationTokenSource())
.ToList();
var tasks = Enumerable.Range(0, 3).Select(x => Task.Run(
() => Counter(cancellationSources[x].Token),
cancellationSources[x].Token
));
cancellationSources[1].Cancel();
await Task.WhenAll(tasks);
Console.ReadLine();
}
public static void Counter(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
// or while(true) and token.ThrowIfCancellationRequested(); to throw instead
for (int i = 0; i < 1000; i++)
{
Console.WriteLine(i);
}
}
}
- 1 回答
- 0 關(guān)注
- 98 瀏覽
添加回答
舉報(bào)