C#如何取消任务?

时间:2017-11-20 09:41:29

标签: c# task

我有一个设计为startstop 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);
}

但上面的代码未能取消任务,请您告诉我如何修复此代码。提前谢谢!

0 个答案:

没有答案