c# - 取消异步任务?
问题描述
我的代码没有正确取消任务,我仍然在我的图表中看到我的系列正在为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;
}
}
解决方案
尝试调用您用来创建传递给的令牌Cancel()
的实际值:CancellationTokenSource
Start
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);
}
推荐阅读
- sql - 根据列值抓取值
- jquery - sortable - 获取放置项指针
- mql4 - Algotrading:如何合并这种类型的追踪止损?
- bash - Bash 剪切和排序问题
- ios - FCM-当用户单击通知时如何区分它是从 Firebase 控制台还是 HTTP 发送
- laravel - 模型在什么时候知道要使用哪个连接
- botframework - 如何为 Skype 机器人实现即时欢迎消息?
- excel - 如果 Excel 工作表公式中的语句为 True,如何添加可计算值
- php - 在 routes.php 文件中获取错误以将它们传递给另一个路由
- excel - 根据用户输入定义数字的小数位