异常日志记录中的空引用异常屏蔽了真正的错误

The*_*ver 3 c# asp.net iis-7 multithreading mutex

我们有一个由网络请求启动的长期运行的流程。为了让进程有时间完成,我们将其分离到一个新线程上,并使用互斥体来确保该进程只有一个实例可以运行。此代码在我们的开发和暂存环境中按预期运行,但在我们的生产环境中失败并出现空引用异常。我们的应用程序日志记录没有捕获任何内容,我们的操作人员报告说它导致了应用程序池崩溃。(这似乎是一个环境问题,但我们必须假设环境配置相同。)到目前为止,我们无法确定空引用在哪里。

以下是应用程序事件日志中的异常:

Exception: System.NullReferenceException
Message: Object reference not set to an instance of an object.
StackTrace:    at Jobs.LongRunningJob.DoWork()
   at System.Threading.ExecutionContext.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()
Run Code Online (Sandbox Code Playgroud)

这是代码(稍微清理过):

public class LongRunningJob: Job
{
    private static Mutex mutex = new Mutex();

    protected override void PerformRunJob()
    {
        var ts = new ThreadStart(LongRunningJob.DoWork);
        var thd = new Thread(ts);
        thd.IsBackground = true;
        thd.Start();
    }

    private static void DoWork()
    {
        var commandTimeOut = 180;

        var from = DateTime.Now.AddHours(-24);
        var to = DateTime.Now;

        if (mutex.WaitOne(TimeSpan.Zero))
        {
            try
            {
               DoSomethingExternal(); // from what we can tell, this is never called
            }
            catch (SqlException sqlEx)
            {
                if (sqlEx.InnerException.Message.Contains("timeout period elapsed"))
                {
                    Logging.LogException(String.Format("Command timeout in LongRunningJob: CommandTimeout: {0}", commandTimeOut), sqlEx);
                }
                else
                {
                    Logging.LogException(String.Format("SQL exception in LongRunningJob: {0}", sqlEx.InnerException.Message), sqlEx);
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(String.Format("Error processing data in LongRunningJob: {0}", ex.InnerException.Message), ex);
            }
            finally
            {
                mutex.ReleaseMutex();
            }
        }
        else
        {
            Logging.LogMessage("LongRunningJob is already running.");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

usr*_*usr 5

为了找到一个,NullReferenceException您基本上要检查每个取消引用操作。我只能看到以下可疑的一个:

ex.InnerException.Message
Run Code Online (Sandbox Code Playgroud)

你不能假设ex.InnerExceptionis 不为空。