簡體   English   中英

取消異步任務?

[英]Cancel async task?

我的代碼未正確取消任務,我仍然看到我的圖中的系列是為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);
        }
    }

    private void InitiateTimerWithButtonUIChange(DispatcherTimer timer, Button buttonSelected, bool isFinished)
    {
        if (!isFinished)
        {
            timer.Start();
            buttonSelected.Background = resourceDictionary["Processing"] as Brush;
        }
        else
        {
            timer.Stop();
            buttonSelected.Background = resourceDictionary["ColourActive"] as Brush;

            // Reset
            time = 0;
        }
    }

嘗試在用於創建傳遞給Start的令牌的實際CancellationTokenSource上調用Cancel()

CancellationTokenSource cancellationTokenSource;
private void StartTest_Click(object sender, RoutedEventArgs e)
{
    if (cancellationTokenSource != null)
    {
        cancellationTokenSource.Cancel();
        cancellationTokenSource.Dispose();
    }

    cancellationTokenSource = new CancellationTokenSource();
    _isRunning = !_isRunning;
    Start(cancellationTokenSource.Token);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM