gpt4 book ai didi

c# - UnobservedTaskException 被抛出,但它由 TaskScheduler.UnobservedTaskException 处理程序和 continuations OnlyOnFaulted 处理程序处理

转载 作者:太空宇宙 更新时间:2023-11-03 13:57:03 25 4
gpt4 key购买 nike

<分区>

我在 TPL 编程方面遇到问题。
我在 [ http://stackoverflow.com/questions/7883052/a-tasks-exceptions-were-not-observed-either-by-waiting-on 上使用@h4165f8ghd4f854d6f8h 解决方案时出现 UnobservedTaskException -the-task-or-accessi/11830087#11830087 ] 来处理异常但仍然得到 UnobservedTaskException。
我也在开始任务之前添加了以下代码:

    TaskScheduler.UnobservedTaskException += (sender, e) =>
{
e.SetObserved();
throw e.Exception;
};

但是 [ http://stackoverflow.com/questions/10874068/exception-thrown-in-task-thread-not-caught-by-unobservedtaskexception ] 告诉它不会捕获每个 TPL 未处理的异常。

我想传播异常直到到达堆栈顶部然后处理它。
有人可以帮助我吗????


@乔恩双向飞碟

您好,我做了一个较小的复现,感谢检查

class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.tplTestOne();
}
public void tplTestOne()
{
TaskScheduler.UnobservedTaskException += (sender, e) =>
{
e.SetObserved();
throw e.Exception;
};
Task tsk_1 = MyClassHere.createHandledTask(() =>
{
double x = 1;
x = (x + 1) / x;
}, false);
Task tsk_2 = MyClassHere.createHandledTask(() =>
{
double y = 0;
throw new Exception("forced_divisionbyzerodontthrowanymore_test"); // here -> System.Exception was unhandled by user code
}, true);
Task tsk_3 = MyClassHere.createHandledTask(() =>
{
double z = 1;
z = (z + 1) / z;
}, true);
Task tsk_4 = MyClassHere.createHandledTask(() =>
{
double k = 1;
k = (k + 1) / k;
}, true);
Console.ReadLine();
}
}

public static class MyClassHere
{
public static void waitForTsk(Task t)
{
try
{
t.Wait();
}
catch (AggregateException ae)
{
ae.Handle((err) =>
{
throw err;
});
}
}

public static void throwFirstExceptionIfHappens(this Task task)
{
task.ContinueWith(t =>
{
var aggException = t.Exception.Flatten();
foreach (var exception in aggException.InnerExceptions)
{
throw exception; // throw only first, search for solution
}
},
TaskContinuationOptions.OnlyOnFaulted); // not valid for multi task continuations
}

public static Task createHandledTask(Action action)
{
return createHandledTask(action, false);
}

public static Task createHandledTask(Action action, bool attachToParent)
{
Task tsk = null;

if (attachToParent)
{
TaskCreationOptions atp = TaskCreationOptions.AttachedToParent;
tsk = Task.Factory.StartNew(action, atp);
}
else
{
tsk = Task.Factory.StartNew(action);
}
tsk.throwFirstExceptionIfHappens();
return tsk;
}

}


谢谢

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com