异步日志记录抛出一个NullReferenceException抛出、日志、NullReferenceException

2023-09-07 14:33:25 作者:拱手河山讨欢

我想以异步方式记录一个MVC 4控制器动作针对.NET 4.0使用AsyncTargetingPack内部的一些信息到SQL Server。我会直接跳到.NET 4.5,但我的应用程序住在Azure和we're还在等待更新 ...

I am trying to asynchronously log some information to SQL Server inside of an MVC 4 controller action targeting .NET 4.0 using the AsyncTargetingPack. I would jump straight to .NET 4.5 but my app lives in Azure and we're still waiting for the update...

这code按预期工作(一排被写入我的数据库抛出没有例外):

This code works as expected (a row is written to my database with no exceptions thrown):

public class SystemActionLogger : ISystemActionLogger
{
    private readonly ActionBlock<Tuple<SystemAction, object>> actionBlock;

    public SystemActionLogger(ISystemActionLogEntryRepository repository)
    {
        actionBlock = new ActionBlock<Tuple<SystemAction, object>>(
            entry => TaskEx.Run(async () =>
                {
                    string data = await JsonConvert.SerializeObjectAsync(entry.Item2);
                    await repository.PersistAsync(new SystemActionLogEntry(entry.Item1, data));
                }));
    }

    public void Log(SystemAction systemAction, object data)
    {
        actionBlock.Post(new Tuple<SystemAction, object>(systemAction, data));
    }
}

这code抛出一个NullReferenceException:

And this code throws a NullReferenceException:

public class SystemActionLogger : ISystemActionLogger
{
    private readonly ActionBlock<Tuple<SystemAction, object>> actionBlock;

    public SystemActionLogger(ISystemActionLogEntryRepository repository)
    {
        actionBlock = new ActionBlock<Tuple<SystemAction, object>>(async entry =>
            {
                string data = await JsonConvert.SerializeObjectAsync(entry.Item2);
                await repository.PersistAsync(new SystemActionLogEntry(entry.Item1, data));
            });
    }

    public void Log(SystemAction systemAction, object data)
    {
        actionBlock.Post(new Tuple<SystemAction, object>(systemAction, data));
    }
}

的NullReferenceException:对象未设置为一个对象的实例

NullReferenceException: "Object reference not set to an instance of an object."

Server stack trace: 
   at System.Web.ThreadContext.AssociateWithCurrentThread(Boolean setImpersonationContext)
   at System.Web.HttpApplication.OnThreadEnterPrivate(Boolean setImpersonationContext)
   at System.Web.LegacyAspNetSynchronizationContext.CallCallbackPossiblyUnderLock(SendOrPostCallback callback, Object state)
   at System.Web.LegacyAspNetSynchronizationContext.CallCallback(SendOrPostCallback callback, Object state)
   at System.Runtime.CompilerServices.TaskAwaiter.<>c__DisplayClassa.<OnCompletedInternal>b__0(Task param0)

Exception rethrown at [0]: 
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__1(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()

我不可见性的例外,因为它是所有外部code。我不明白为什么code中的第二块失败。这是code我原来写的。

I have no visibility into the exception as it is all external code. I don't understand why the second block of code fails. This is the code I originally wrote.

我究竟做错了什么?

推荐答案

我只是有一个非常类似的问题(从AssociateWithCurrentThread使用日志记录任务时NullReference)。

I was just having a very similar issue (NullReference from AssociateWithCurrentThread when using a logging task).

我遇到的问题是,原来的动作并没有等待完成测井任务,所以当日志完成,并试图重新加入原来的线程nullReference被抛出,因为原来的线程终止。

The issue I was having was that the original action did not await the completion of the logging task, so when the log finishes and tries to rejoin the original thread a nullReference is thrown because the original thread has terminated.

这是解决了,我要确保请求控制器等待记录功能。

This was solved for me by making sure that the request controller awaited the logging function.