【发布时间】:2016-05-25 04:39:17
【问题描述】:
我正在尝试通过按开始按钮来迭代 for 循环并通过按停止按钮来停止它。我正在使用await Task.Run(() => 它以预期的方式工作。但是当我再次按下开始按钮时,我在Application.Run(new Form1()); 中得到了 TargetInvokationException。
下面是我的代码
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CancellationTest
{
public partial class Form1 : Form
{
private readonly SynchronizationContext synchronizationContext;
private DateTime previousTime = DateTime.Now;
CancellationTokenSource cts = new CancellationTokenSource();
public Form1()
{
InitializeComponent();
synchronizationContext = SynchronizationContext.Current;
}
private async void ButtonClickHandlerAsync(object sender, EventArgs e)
{
button1.Enabled = false;
var count = 0;
CancellationToken token = cts.Token;
await Task.Run(() =>
{
try
{
for (var i = 0; i <= 5000000; i++)
{
token.ThrowIfCancellationRequested();
UpdateUI(i);
count = i;
}
}
catch (System.OperationCanceledException)
{
MessageBox.Show("Canceled");
}
}, token);
label1.Text = @"Counter " + count;
button1.Enabled = true;
}
public void UpdateUI(int value)
{
var timeNow = DateTime.Now;
if ((DateTime.Now - previousTime).Milliseconds <= 50) return;
synchronizationContext.Post(new SendOrPostCallback(o =>
{
label1.Text = @"Counter " + (int)o;
}), value);
previousTime = timeNow;
}
private void button2_Click(object sender, EventArgs e)
{
cts.Cancel();
}
}
}
谁能解释为什么会发生这种情况以及如何解决这个问题。
【问题讨论】:
-
修复未处理的异常诊断,不惜一切代价。对于这样的异常,您总是想知道 InnerException。单击异常助手对话框中的详细信息链接。现在很容易看出 CancellationToken 已经过时了。
标签: c# multithreading winforms cancellation cancellationtokensource