c# - 如何让 Elmah 与 UnobservedTaskException 一起工作

标签 c# asp.net-mvc task-parallel-library elmah

我正在开发一个 asp.net mvc 应用程序。我的应用程序的架构如下:

  1. 一个DBAccessLayer//访问数据库的层
  2. 一个 ServiceLayer//连接 1 和 3 的层。
  3. 一个 WebLayer//Web UI 层

我想记录所有应用程序异常,包括 TaskScheduler.UnobservedTaskException 事件中的异常。

我已经测试过如下:

protected void Application_Start()
{
    ...
    TaskScheduler.UnobservedTaskException += (object sender, UnobservedTaskExceptionEventArgs excArgs) =>
    {
      ErrorSignal.FromCurrentContext().Raise(excArgs.Exception);      
      excArgs.SetObserved();
    };
}

但是当 UnobservedTaskException 事件被触发时,应用程序崩溃,异常如​​下:

    System.ArgumentNullException was unhandled
         Message=Value cannot be null.
         Parameter name: context
         Source=Elmah
         ParamName=context
    StackTrace:
         at Elmah.ErrorSignal.FromContext(HttpContext context) in c:\builds\ELMAH\src\Elmah\ErrorSignal.cs:line 67
         at MyMvcApplication.<Application_Start>b__0(Object sender, UnobservedTaskExceptionEventArgs excArgs) in ...\Global.asax.cs:line 82
         at System.Threading.Tasks.TaskScheduler.PublishUnobservedTaskException(Object sender, UnobservedTaskExceptionEventArgs ueea)
         at System.Threading.Tasks.TaskExceptionHolder.Finalize()

另外,我在WebLayer的global.asax.cs中放置了UnobservedTaskException事件,当DBAccessLayer和ServiceLayer有未观察到的异常时是否可以触发?

谢谢。

最佳答案

当您的处理程序被触发时,似乎没有 HttpContext,因为计划任务没有作为 HTTP 请求的一部分运行。而不是使用

ErrorSignal.FromCurrentContext().Raise

你可以用

ErrorLog.GetDefault(null).Log

关于c# - 如何让 Elmah 与 UnobservedTaskException 一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9576451/

相关文章:

c# - 使用 C# 将 word 文档转换为文本文档

c# - 如何在 XML Comment <return> 注释中指定类型

c# - 如何获取当前函数的名称?

c# - 为什么分配任务然后等待它允许并行运行

c# - 如何使ConcurrentExclusiveSchedulerPair与async和await一起使用

c# - 单点触控 : UIPicker as first responder for a UITextbox

c# - 如何从 ClaimsPrincipal 中删除 ClaimsIdentity

javascript - 无法在 JavaScript 中迭代列表

c# - 将对象转换为 urlencoded 字符串

c# - .NET 编译器——是否内置了嵌套循环优化?