0

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

  1. connect to DB
  2. Call Sproc
  3. 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

  1. throw new ApplicationException("Hello from LogMessageToSIFDB()");
  2. connect to DB
  3. Call Sproc
  4. 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.

4

1 回答 1

1

使用Tasks,期望您将以Task某种方式观察到异常:通过使用Wait()or Result(抛出异常,包含在 中AggregateException)或直接通过访问其Exception属性。

如果您不这样做并且Task收集垃圾,它的终结器将抛出异常,这将导致整个过程停止(尽管 .Net 4.5 改变了这一点,但终结器将不再抛出)。但是您必须记住,GC 不是确定性的,并且Task可能仅在很长一段时间后才会收集,这很可能是您看不到任何东西的原因。

你应该做的是以某种方式观察异常。如果您想异步执行此操作,您可以使用ContinueWith()with OnlyOnFaulted。但这里更简单的方法是使用普通的try- catch

Task.Factory.StartNew(() =>
{
    try
    {
        LogMessageToSIFDB(inClientID, tmpByte, Modified, SIF_MessageID, SIF_TimeStamp));
    }
    catch (Exception ex)
    {
        // perform your logging here
    }
});
于 2012-07-20T00:12:37.620 回答