我有这个例子:
var asyncTasks = new Task[list.Length];
for (int i = 0; i< list.Length; i++)
{
asyncTasks[i] = tf(cts.Token, list[i]);
}
await Task.WhenAll(asyncTasks);
//do other stuffs when all tasks completed
当然还有我的async
函数,称为tf
:
private async Task tf(CancellationToken token , string list)
{
try
{
await Task.Run(() =>
{
if (token.IsCancellationRequested)
{
MessageBox.Show("Stopped", "Operation Aborted");
token.ThrowIfCancellationRequested();
cts = new CancellationTokenSource();
}
// do something
}, token);
}catch{}
cts = new CancellationTokenSource();
}
编辑:在我的取消按钮中,我声明:cts.Cancel();
此方法对我来说是正确的,因为它同时执行一系列任务,但是我认为我无法发送取消请求的令牌,因为所有已分配的cts.Token
是有效的,所以如果在另一个按钮中,我尝试cts.Cancel()
无效。我该怎么做,但要使取消令牌请求有效?
答案 0 :(得分:0)
问题是我在任务功能结束时每次使用cts = new CancellationTokenSource();
重置每次调用的令牌
已修复功能:
private async Task tf(CancellationToken token , string list)
{
try
{
await Task.Run(() =>
{
if (token.IsCancellationRequested)
{
MessageBox.Show("Stopped", "Operation Aborted");
token.ThrowIfCancellationRequested();
cts = new CancellationTokenSource();
}
// do something
}, token);
}catch{}
}