在使用.NET 4.0进行并行编程时,我显然不知道自己在做什么.我有一个简单的Windows应用程序启动任务做一些盲目的工作(输出数字1-1000).我在中途进行了大量的停顿,以模拟一个长时间运行的过程.当这个长时间暂停发生时,如果我点击Stop按钮,它的事件处理程序会调用CancellationTokenSource的Cancel方法.我不希望在Stop按钮的事件处理程序中进行任何进一步处理(在这种情况下,输出消息),直到取消的任务完成其当前迭代.我该怎么做呢?我尝试在Stop按钮的事件处理程序中使用Task.WaitAll等,但这只会抛出一个未处理的AggregateException.如果按上述方式运行,这里的代码将有助于解释我的问题:
private Task t;
private CancellationTokenSource cts;
public Form1()
{
InitializeComponent();
}
private void startButton_Click(object sender, EventArgs e)
{
statusTextBox.Text = "Output started.";
// Create the cancellation token source.
cts = new CancellationTokenSource();
// Create the cancellation token.
CancellationToken ct = cts.Token;
// Create & start worker task.
t = Task.Factory.StartNew(() => DoWork(ct), ct);
}
private void DoWork(CancellationToken ct)
{
for (int i = 1; i <= 1000; i++)
{
ct.ThrowIfCancellationRequested();
Thread.Sleep(10); // Slow down for text box outout. …Run Code Online (Sandbox Code Playgroud)