C#:任务取消不起作用 (CancellationTokenSource)
C#: Task cancellation not working (CancellationTokenSource)
我有一些很长的 运行ning 代码,我想将其 运行 作为 Task
并在需要时使用 CancellationTokenSource
取消,但似乎无法取消当调用 tokenSource.Cancel()
时,我的任务保持 运行ning 工作(没有抛出异常)。
可能遗漏了一些明显的东西?
缩减示例如下:
bool init = false;
private void Button1_Click(object sender, EventArgs e)
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
Task task = new Task(() =>
{
while (true)
{
token.ThrowIfCancellationRequested();
if (token.IsCancellationRequested)
{
Console.WriteLine("Operation is going to be cancelled");
throw new Exception("Task cancelled");
}
else
{
// do some work
}
}
}, token);
if (init)
{
tokenSource.Cancel();
button1.Text = "Start again";
init = false;
} else
{
try
{
task.Start();
} catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
button1.Text = "Cancel";
init = true;
}
}
您代码中的主要问题是您没有存储 tokenSource
。第二次 Button1_Click
调用取消的令牌不同于您在第一次调用期间传递给任务的令牌。
第二个问题是您一遍又一遍地创建新任务,但您的逻辑表明您想要一个应该在第一次点击时创建并在第二次点击时终止的任务。
我有一些很长的 运行ning 代码,我想将其 运行 作为 Task
并在需要时使用 CancellationTokenSource
取消,但似乎无法取消当调用 tokenSource.Cancel()
时,我的任务保持 运行ning 工作(没有抛出异常)。
可能遗漏了一些明显的东西?
缩减示例如下:
bool init = false;
private void Button1_Click(object sender, EventArgs e)
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
Task task = new Task(() =>
{
while (true)
{
token.ThrowIfCancellationRequested();
if (token.IsCancellationRequested)
{
Console.WriteLine("Operation is going to be cancelled");
throw new Exception("Task cancelled");
}
else
{
// do some work
}
}
}, token);
if (init)
{
tokenSource.Cancel();
button1.Text = "Start again";
init = false;
} else
{
try
{
task.Start();
} catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
button1.Text = "Cancel";
init = true;
}
}
您代码中的主要问题是您没有存储 tokenSource
。第二次 Button1_Click
调用取消的令牌不同于您在第一次调用期间传递给任务的令牌。
第二个问题是您一遍又一遍地创建新任务,但您的逻辑表明您想要一个应该在第一次点击时创建并在第二次点击时终止的任务。