我有一个非常奇怪的问题,现在这是我的代码:
namespace TaskParallelTest
{
using System.Threading;
using System.Threading.Tasks;
using System;
using System.IO;
public class Program
{
static Program()
{
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
}
private static void DoPrint(int id, CancellationToken cToken)
{
Thread.Sleep(100);
if (!cToken.IsCancellationRequested)
{
Console.WriteLine("Id is:" + id + ";Current State:" + cToken.IsCancellationRequested);
cToken.Register(() => Console.WriteLine("Rollback for:" + id));
}
}
static void Main(string[] args)
{
CancellationTokenSource cTokenSource = new CancellationTokenSource();
Task.Run(() =>
{
for (int i = 1; i < 6; i++)
{
cTokenSource.Token.ThrowIfCancellationRequested();
DoPrint(i, cTokenSource.Token);
}
}, cTokenSource.Token);
Random r = new Random();
Thread.Sleep(400);
cTokenSource.Cancel(true);
Thread.Sleep(10000);
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("OK");
Console.ReadLine();
}
private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
File.WriteAllText("C:\\Resume\\Error.txt", e.Exception.StackTrace);
e.SetObserved();
}
}
}
让我感到生气的原因是为什么无法捕获“UnobservedTaskException”事件?我使用了GC.Collect()和Thread.Sleep(),但没有任何帮助......?
有时,“Error.txt”没有被创建,有时候,创建的文件没有任何东西......?
【解决了 - 现在根据建议,这里是答案】
1)请注意,我应该删除“取消”并在此处模拟例外:
static void Main(string[] args)
{
CancellationTokenSource cTokenSource = new CancellationTokenSource();
Task.Run(() =>
{
for (int i = 1; i < 6; i++)
{
if (i==5)
{
throw new Exception("Error occured!");
}
DoPrint(i, cTokenSource.Token);
}
},cTokenSource.Token)
.ContinueWith
(
t =>
{
Console.WriteLine("Error has happened now.");
Console.WriteLine(t.IsFaulted);
},
TaskContinuationOptions.OnlyOnFaulted
);
Thread.Sleep(400);
//cTokenSource.Cancel();
//Thread.Sleep(2000);
GC.Collect();
GC.WaitForPendingFinalizers();
//Thread.Sleep(6000);
Console.WriteLine("OK");
Console.ReadLine();
}
2)然后展平异常(因为这是一个聚合异常):
private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
foreach (var item in e.Exception.Flatten().InnerExceptions)
{
Console.WriteLine(item.StackTrace);
}
e.SetObserved();
}
答案 0 :(得分:0)
如果针对特定令牌抛出OperationCanceledException
,并且这与您在创建任务时传递的令牌相同 - 它不会被视为未处理的\ unobserved异常,因为它只是正常的预期取消流。此异常将仅将任务状态设置为已取消。在你的情况下也是如此:
var task = Task.Run(() =>
{
for (int i = 1; i < 6; i++)
{
// this exception is associated with cTokenSource.Token
cTokenSource.Token.ThrowIfCancellationRequested();
DoPrint(i, cTokenSource.Token);
}
}, cTokenSource.Token); // and this is the same token you pass when creating a task
如果不是这种情况(例如,在创建任务时传递不同的标记) - 异常将被UnobservedTaskException处理程序截获。
问题是:为什么你想要将此异常视为未观察到的?您希望任务可以取消,然后取消它,它现在处于已取消状态。什么都没有观察到\未处理。