How to use Elmah to log the TaskScheduler.UnobservedTaskException exceptions

Answered How to use Elmah to log the TaskScheduler.UnobservedTaskException exceptions

  • Friday, March 02, 2012 2:34 PM
     
     

    I'm developing a asp.net mvc application. And I want to log all application exceptions.

    After googled, I found the best solution is to use the Elmah to log exceptions. But I can't find anyone tell if it's possible to log the exceptions  in the TaskScheduler.UnobservedTaskException event with Elmah.

    Can anybody give a clue?

    Thanks.

All Replies

  • Sunday, March 04, 2012 4:09 PM
    Owner
     
     Proposed

    I've never used Elmah, but doing a quick search on Bing for how to use it programmatically, you could try something like:

    TaskScheduler.UnobservedTaskException += (s,e) =>
    {
        ErrorSignal.FromCurrentContext().Raise(e.Exception);
        e.SetObserved();
    };

    I hope that helps.

  • Monday, March 05, 2012 1:29 AM
     
      Has Code

    I've tested to do as below:

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

    but when the UnobservedTaskException event is fired, the application crashed with exception as below:

    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()

  • Monday, March 05, 2012 1:50 AM
    Owner
     
     Answered

    I see. Elmah is expecting to only be used in the context of an HTTP request, and UnobservedTaskException is occurring later on in the finalizer thread.  You'll need to find out how to log an exception to Elmah more generally.

    • Marked As Answer by zhangzhzh Tuesday, March 06, 2012 2:21 AM
    •  
  • Monday, March 05, 2012 7:35 AM
     
     

    Maybe it's impossible to do it.

    Thanks.