C#学习教程:异步日志记录抛出NullReferenceException我会直接跳到.NET4.5,但我的应用程序存在于Azure中,我们仍在等待更新......此代码按预期工作(一行写入我的数据库,没有抛出异常):publicclassSystemActionLogger:ISystemActionLogger{privatereadonlyActionBlockactionBlock;publicSystemActionLogger(ISystemActionLogEntryRepositoryrepository){actionBlock=newActionBlock(entry=>TaskEx.Run(async()=>{stringdata=awaitJsonConvert.SerializeObjectAsync(entry.Item2);awaitrepository.PersistAsync(newSystemActionLogEntry(entry).Item1,数据));}));}publicvoidLog(SystemActionsystemAction,objectdata){actionBlock.Post(newTuple(systemAction,data));}}此代码抛出NullReferenceException发生:publicclassSystemActionLogger:ISystemActionLogger{privatereadonlyActionBlockactionBlock;publicSystemActionLogger(ISystemActionLogEntryRepositoryrepository){actionBlock=newActionBlock(asyncentry=>{stringdata=awaitJsonConvert.Asserial2)awaitrepository.PersistAsync(newSystemActionLogEntry(entry.Item1,data));});}publicvoidLog(SystemActionsystemAction,objectdata){actionBlock.Post(newTuple(systemAction,data));}}NullReferenceException:“对象引用未设置为对象的实例”服务器堆栈跟踪:在System.Web.ThreadContext.AssociateWithCurrentThread(BooleansetImpersonationContext)System.Runtime.CompilerServices.TaskAwaiter.c__DisplayClassa.b__0(任务参数0)中的.CallCallback(SendOrPostCallback回调,对象状态)在[0]处重新抛出异常:System.Runtime.CompilerServices.AsyncMethodBuilderCore.b__1(对象状态)在System.Threading.ExecutionContext.RunInternal(ExecutionContextexecutionContext,ContextCallback回调,对象状态,布尔值preserveSyncCtx)在System.Threading.ExecutionContext.Run(ExecutionContextexecutionContext,ContextCallback回调,对象状态,布尔值preserveSyncCtx)在System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()在System.Threading.ThreadPoolWorkQueue.Dispatch()我看不到异常,因为它都是外部代码我不明白为什么第二个代码块失败。这是我最初写的代码。我究竟做错了什么?我刚刚遇到了一个非常相似的问题(使用日志记录任务时来自AssociateWithCurrentThread的NullReference)。我遇到的问题是原始线程不会等待日志记录任务完成,因此当日志完成并尝试重新加入原始线程时,会抛出nullReference,因为原始线程已终止。这可以通过确保请求控制器等待日志记录功能来解决。Dataflow仅适用于.NET4.5。不支持在.NET4.0上运行它这一事实,这可能是您看到虚假异常的原因。当我的Web服务异步调用另一个WCF服务时,.net4.5出现了这个问题。我只是附加了一个简短的Wait()因为我不关心响应(遥测事件)。以上就是C#学习教程:AsynchronousloggingthrowsNullReferenceException的全部内容分享。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注——publicstaticvoidEvent(stringkey,stringmessage){Telemetry.Event(key,message).Wait(100);}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: