我的代碼沒有正確取消任務(wù),我仍然看到我的圖表中的系列正在為循環(huán)中的下一個(gè)系列繪制foreach...不確定我在這里做錯(cuò)了什么,因?yàn)槲蚁胪顺霾⑷∠挟惒酱藭r(shí)的任務(wù)...有什么想法嗎? 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貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個(gè)贊
嘗試調(diào)用您用來創(chuàng)建傳遞給的令牌的Cancel()實(shí)際內(nèi)容: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 關(guān)注
- 149 瀏覽
添加回答
舉報(bào)
0/150
提交
取消