Net*_*orm 6 c# task task-parallel-library cancellationtokensource
所以我有这个代码:
//CancelationToken
CancellationTokenSource src = new CancellationTokenSource();
CancellationToken ct = src.Token;
ct.Register(() => Console.WriteLine("Abbruch des Tasks"));
//Task
Task t = new Task(() =>
{
System.Threading.Thread.Sleep(1000);
if (ct.IsCancellationRequested)
{
try
{
//Throw
ct.ThrowIfCancellationRequested();
}
catch (OperationCanceledException)
{
Console.WriteLine(
"ThrowIfCancellationRequested() liefert eben eine Exception");
}
}
}, ct);
//Run Task and Cancel
t.Start();
src.CancelAfter(350);
t.Wait();
// Get Information
Console.WriteLine("Canceled: {0} . Finished: {1} . Error: {2}",
t.IsCanceled, t.IsCompleted, t.IsFaulted);
Run Code Online (Sandbox Code Playgroud)
所以在这种情况下我取消了我的任务,但我的输出最后是:"取消:假.完成:真.错误:错误"
在我看来,它应该是"取消:真实.完成:假".为什么我得到这个结果?因为我试图抓住异常?
我试过没有try-catch块,但是由于OperationCanceledException,我的程序停止了.有人能帮助我吗?
您正在吞噬异常,因此任务在您实际处理异常时被标记为已完成,并且不会向外传播.
相反,不要在委托中捕获异常,将其捕获到外部:
void Main()
{
CancellationTokenSource src = new CancellationTokenSource();
CancellationToken ct = src.Token;
ct.Register(() => Console.WriteLine("Abbruch des Tasks"));
Task t = Task.Run(() =>
{
System.Threading.Thread.Sleep(1000);
ct.ThrowIfCancellationRequested();
}, ct);
src.Cancel();
try
{
t.Wait();
}
catch (AggregateException e)
{
// Don't actually use an empty catch clause, this is
// for the sake of demonstration.
}
Console.WriteLine("Canceled: {0} . Finished: {1} . Error: {2}",
t.IsCanceled, t.IsCompleted, t.IsFaulted);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3314 次 |
| 最近记录: |