任务被取消了

时间:2017-04-17 20:23:06

标签: c# wpf

我正在执行一项任务。关闭窗口时,我尝试使用取消令牌源取消任务。每次关闭窗口时都不会发生错误。只是有时。请看一下我得到的错误

enter image description here

    private CancellationTokenSource dotIndicatorTokenSource;
    private void BlinkDotIndicator()
    {

        var halfPeriod = 200;

        dotIndicatorTokenSource = new CancellationTokenSource();
        Task.Factory.StartNew(() =>
        {
            while (true)
            {
                Dispatcher.Invoke(() =>
                {
                    connectionIndicatorDotImg.Visibility = Visibility.Hidden;
                });
                Thread.Sleep(halfPeriod);

                Dispatcher.Invoke(() =>
                {
                    connectionIndicatorDotImg.Visibility = Visibility.Visible;
                });

                Thread.Sleep(halfPeriod);

                if (dotIndicatorTokenSource.IsCancellationRequested)
                {
                    break;
                }

            }
        }, dotIndicatorTokenSource.Token);

    }


    private void Window_Closing(object sender, CancelEventArgs e)
    {
        if (dotIndicatorTokenSource != null)
            dotIndicatorTokenSource.Cancel();
    }

1 个答案:

答案 0 :(得分:2)

运行代码时,检查取消是否在之前和之后以及之间是否有待处理。这样,如果在操作期间取消,则不会执行下一个Dispatcher函数。

        while (true)
        {
            if (dotIndicatorTokenSource.IsCancellationRequested)
            {
                break;
            }

            Dispatcher.Invoke(() =>
            {
                connectionIndicatorDotImg.Visibility = Visibility.Hidden;
            });
            Thread.Sleep(halfPeriod);

            if (dotIndicatorTokenSource.IsCancellationRequested)
            {
                break;
            }

            Dispatcher.Invoke(() =>
            {
                connectionIndicatorDotImg.Visibility = Visibility.Visible;
            });

            Thread.Sleep(halfPeriod);

            if (dotIndicatorTokenSource.IsCancellationRequested)
            {
                break;
            }

        }