取消异步任务?

我的代码没有正确取消任务,我仍然看到我的图表中的系列正在为循环中的下一个系列绘制foreach...不确定我在这里做错了什么,因为我想退出并取消所有异步此时的任务...有什么想法吗?


    private void StartTest_Click(object sender, RoutedEventArgs e)

    {

        var cancellationTokenSource = new CancellationTokenSource();

        if (_isRunning)

        {

            cancellationTokenSource.Cancel();

        }


        _isRunning = !_isRunning;

        Start(cancellationTokenSource.Token);

    }


    private async void Start(CancellationToken cancellationToken)

    {

        foreach (var buttonSelected in selectedButtons)

        {

            // If cancellation requested

            if (cancellationToken.IsCancellationRequested)

                break;


            // Retrieve series to reflect changes on

            var seriesToChange = Model.Series.Where(x => x.Title == buttonSelected.Name).ToArray();


            // Create timer

            var timerForPlotting = new DispatcherTimer();

            if (seriesToChange .Length == 1)

            {

                // Set the series to visible

                seriesToChange [0].IsVisible = true;


                timerForPlotting.Interval = TimeSpan.FromMilliseconds(50);

                timerForPlotting.Tick += (object s, EventArgs a) => PlotSeriesPoints_Tick(s, a, seriesToChange [0]);

            }


            // Start

            InitiateTimerWithButtonUIChange(timerForPlotting, buttonSelected, false);


            // Set the task to only take a couple of seconds

            await Task.Delay(2000);


            // End

            InitiateTimerWithButtonUIChange(timerForPlotting, buttonSelected, true);

        }

    }

FFIVE
浏览 118回答 1
1回答

MM们

尝试调用您用来创建传递给的令牌的Cancel()实际内容:CancellationTokenSourceStartCancellationTokenSource cancellationTokenSource;private void StartTest_Click(object sender, RoutedEventArgs e){    if (cancellationTokenSource != null)    {        cancellationTokenSource.Cancel();        cancellationTokenSource.Dispose();    }    cancellationTokenSource = new CancellationTokenSource();    _isRunning = !_isRunning;    Start(cancellationTokenSource.Token);}
打开App,查看更多内容
随时随地看视频慕课网APP