尝试学习任务、等待和取消。
从我认为来自 MSDN 的一个简单示例开始。
Task.Wait 方法(CancellationToken)
作为控制台应用程序,它按预期运行。
相同的代码在 WPF 中没有按预期运行。
在 WPF t2 中运行到完成 - 行任务完成在调试中打印。
它在 0 到 100000000 之间遇到 OperationCanceledException,但 t2 继续运行。
(注意必须将其更改为 ctr < Int32.MaxValue 否则它永远不会完成)
在 .NET 4.5 上,也尝试过 4.51
public void TestCancel1()
{
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
Task.Run(() =>
{
cts.Cancel();
if (token.IsCancellationRequested)
Debug.WriteLine("Cancellation requested in Task {0}.",
Task.CurrentId);
}, token);
Task t2 = Task.Run(() =>
{
Debug.WriteLine(Int32.MaxValue.ToString());
for (Int32 ctr = 0; ctr < Int32.MaxValue; ctr++) //
{
if (ctr % 100000000 == 0)
Debug.WriteLine(ctr.ToString());
}
Debug.WriteLine("Task {0} finished.",
Task.CurrentId);
});
try
{
t2.Wait(token);
}
catch (OperationCanceledException)
{
Debug.WriteLine("OperationCanceledException in Task {0}: The operation was cancelled.",
t2.Id);
}
}
控制台应用程序有问题
这里是代码
static void Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
Task.Run(() =>
{
Thread.Sleep(1000); // change number and will get a differnt last ctr
cts.Cancel();
if (token.IsCancellationRequested)
Console.WriteLine("Cancellation requested in Task {0}.",
Task.CurrentId);
}, token);
Task t2 = Task.Run(() =>
{
Console.WriteLine(Int32.MaxValue.ToString());
for (int ctr = 0; ctr < Int32.MaxValue; ctr++)
{
Console.WriteLine(ctr.ToString());
if (ctr % 100000000 == 0) Console.WriteLine(ctr.ToString());
}
Console.WriteLine("Task {0} finished.",
Task.CurrentId);
});
try
{
t2.Wait(token);
}
catch (OperationCanceledException)
{
Console.WriteLine("OperationCanceledException in Task {0}: The operation was cancelled.",
t2.Id);
}
}
添加了 ThrowIfCancellationRequested
我在该行收到错误 OperationCancelException is unhandled by user code
Task t2 = Task.Run(() =>
{
Debug.WriteLine(Int32.MaxValue.ToString());
for (Int32 ctr = 0; ctr < Int32.MaxValue; ctr++) //
{
if (ctr % 100000000 == 0)
{
Debug.WriteLine(ctr.ToString() + " " + token.IsCancellationRequested.ToString());
}
if (token.IsCancellationRequested)
token.ThrowIfCancellationRequested();
}
Debug.WriteLine("Task {0} finished.",
Task.CurrentId);
}); //, token);
好的,我知道这越来越长
了 来自 Microsoft 的那个样本充其量是误导 - 为什么你会有一个没有真正取消的 Cancel 样本
来验证为什么 Rohit 说我添加了以下内容
果然我可以在新闻发布前看到更多的通行证任何继续的键
catch (OperationCanceledException)
{
Console.WriteLine("OperationCanceledException in Task {0}: The operation was cancelled.",
t2.Id);
Thread.Sleep(10);
Console.WriteLine("exit exception");
}