[英]C#: Task cancellation not working (CancellationTokenSource)
我有一些長時間運行的代碼,我想作為Task
運行並在需要時使用CancellationTokenSource
但取消似乎不起作用,因為在tokenSource.Cancel()
時我的任務繼續運行(沒有拋出異常)。
可能遺漏了一些明顯的東西?
縮減示例如下:
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
調用取消了與您在第一次調用期間傳遞給任務不同的令牌。
第二個問題是您一遍又一遍地創建新任務,但您的邏輯表明您想要一個任務,該任務應該在第一次單擊時創建並在第二次單擊時終止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.