【发布时间】:2019-08-09 20:30:56
【问题描述】:
我的代码没有正确取消任务,我仍然在图表中看到我的系列正在为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;
}
}
【问题讨论】:
-
StartTest_Click方法中的逻辑看起来完全是古怪的。 -
您总是在重新创建 CancellationTokenSource,因此正在运行的任务中使用的不是您要取消的。
标签: c# async-await