I am using II6. I have a Method(LogMessageToSIFDB) that I assume had an exception,
Task.Factory.StartNew(() => LogMessageToSIFDB(inClientID, tmpByte, Modified, SIF_MessageID, SIF_TimeStamp));
The method is quite simple
- connect to DB
- Call Sproc
- Close connection
The DB connection now works fine. The problem I am having is if an exception occurs nothing gets logged anywhere.
If I change up the logic flow, the SProc doesn’t get called and nothing gets logged to Events or anything
- throw new ApplicationException(“Hello from LogMessageToSIFDB()”);
- connect to DB
- Call Sproc
- Close connection
In a nutshell, this doesn’t do anything that causes something to get logged.
Task.Factory.StartNew(() => { throw new ApplicationException("Hello from LogMessageToSIFDB()"); });
Here is what I’m trying to do. I have this code in a DLL that implements an interface that Engineering gave me. They pass in a stream that is an XML message. I need to modify that message. I also need to log the original message.
Logging the message to the DB would just cause the IIS thread to block longer, so I figured I would just create a task and let it run async. If the call doesn’t work once in a while, I really don’t care, but if I’m ever debugging a current issue, I need to see an error message.
I was hoping that an unhandled exception in the task would just crop up in the Event Log, but I’m not seeing anything anywhere.
Async logging is not a requirement, but it is preferred. Worst case is just to remove the Task and let it run in sync.
With
Tasks, the expectation is that you are going to observe the exception of theTasksomehow: by usingWait()orResult(which throw the exception, enclosed in anAggregateException) or directly by accessing itsExceptionproperty.If you don’t do that and the
Taskgets garbage collected, its finalizer will throw the exception, which will bring the whole process down (although .Net 4.5 changes that, the finalizer will no longer throw). But you have to remember that GC is not deterministic and theTaskmay be collected only after a long time, which is most likely why you don’t see anything.What you should do is to somehow observe the exception. If you want to do it asynchronously, you can use
ContinueWith()along withOnlyOnFaulted. But an easier way here is to use a normaltry–catch: