问题:我想在控制台应用程序中为未处理的异常定义一个全局异常处理程序.在asp.net中,可以在global.asax中定义一个,在windows应用程序/服务中,可以定义如下
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyExceptionHandler);
Run Code Online (Sandbox Code Playgroud)
但是,如何为控制台应用程序定义全局异常处理程序?
currentDomain似乎不起作用(.NET 2.0)?
编辑:
唉,愚蠢的错误.
在VB.NET中,需要在currentDomain前添加"AddHandler"关键字,否则在IntelliSense中看不到UnhandledException事件......
这是因为VB.NET和C#编译器对事件处理的处理方式不同.
有了System.Threading.Tasks.Task<TResult>,我必须管理可能抛出的异常.我正在寻找最好的方法.到目前为止,我已经创建了一个基类来管理调用中的所有未捕获的异常.ContinueWith(...)
我想知道是否有更好的方法可以做到这一点.或者即使这是一个很好的方法.
public class BaseClass
{
protected void ExecuteIfTaskIsNotFaulted<T>(Task<T> e, Action action)
{
if (!e.IsFaulted) { action(); }
else
{
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
{
/* I display a window explaining the error in the GUI
* and I log the error.
*/
this.Handle.Error(e.Exception);
}));
}
}
}
public class ChildClass : BaseClass
{
public void DoItInAThread()
{
var context = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew<StateObject>(() => this.Action())
.ContinueWith(e => this.ContinuedAction(e), context);
}
private void ContinuedAction(Task<StateObject> e)
{
this.ExecuteIfTaskIsNotFaulted(e, () => …Run Code Online (Sandbox Code Playgroud) 我在.NET 4.0中使用TPL(任务并行库).我想通过使用Thread.GetDomain().UnhandledException事件集中处理所有未处理异常的处理逻辑.但是,在我的应用程序中,从未使用TPL代码启动的线程触发事件,例如Task.Factory.StartNew(...).如果我使用类似的东西,事件确实会被解雇new Thread(threadStart).Start().
这篇MSDN文章建议使用Task.Wait()来捕获AggregateException使用TPL的时间,但这不是我想要的,因为这种机制不够"集中".
有没有人遇到过同样的问题,还是仅仅是我?你对此有什么解决方案吗?
.net multithreading .net-4.0 task-parallel-library unobserved-exception