我的代碼沒有正確取消任務,我仍然看到我的圖表中的系列正在為循環中的下一個系列繪制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); } }
1 回答

MM們
TA貢獻1886條經驗 獲得超2個贊
嘗試調用您用來創建傳遞給的令牌的Cancel()實際內容:CancellationTokenSourceStart
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);
}
- 1 回答
- 0 關注
- 143 瀏覽
添加回答
舉報
0/150
提交
取消