1

我知道我可以处理UnobservedTaskException以防止在终结器运行在对象上时终止我的应用程序的任何未观察到的异常。处理未查看任务异常

但是,我不确定我应该在何时或何时为此事件设置处理程序。在TaskScheduler类中的事件本身的XML文档说:

/// This AppDomain-wide event provides a mechanism to prevent exception 
/// escalation policy (which, by default, terminates the process) from triggering. 
/// Each handler is passed a <see cref="T:System.Threading.Tasks.UnobservedTaskExceptionEventArgs"/> 
/// instance, which may be used to examine the exception and to mark it as observed. 

这是否意味着我只需要在整个的AppDomain一个处理程序?并且所有未观察到的任务异常将由此处理?

或者我需要每个程序集/每个类的处理程序,并且只有该程序集/类中任务的未观察到的异常将转到该处理程序?

回答

2

每个应用程序域都是。这是一个关闭Task类的静态事件,您应该确保在逻辑应用程序启动时挂钩。因此,对于控制台应用程序,只需在开始任何其他工作之前将其挂接在Main中。对于ASP.NET应用程序,只需将其挂接到Global.asax Application_Start即可。对于Windows服务,请在OnStart中。

+0

这是我的想法,感谢您的答复。 – Lyall 2012-02-25 15:03:17

+0

@Drew Marsh嗨,我做到了,但没有解决在这里:http://stackoverflow.com/questions/11831844/unobservedtaskexception-being-throw-but-it-is-handled-by-a-taskscheduler-unobser – newway 2012-08-07 19:19:58