我有一个设计为start
和stop
Task
的按钮,如下所示:
public bool cancelFlag = false;
private void btn_Find_Click(object sender, RoutedEventArgs e)
{
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
if(cancelFlag)
{
cancelFlag = false;
tokenSource.Cancel();
Hint("Searching Canceled!");
}
else
{
cancelFlag = true;
Hint("Start Searching...");
}
Task.Factory.StartNew(() =>
{
if(!token.IsCancellationRequested)
{
Matching_Process_Thread();
}
else
{
return;
}
}, token);
}
但上面的代码未能取消任务,请您告诉我如何修复此代码。提前谢谢!