You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Object reference not set to an instance of an object exception in NotifySynchronizationContextOfCompletion() #40463
I am not sure if this is the right place to post this issue but I tried on stackoverflow before and did not get any respone.
Description
I have an application running on .net core 3.1 that reads frames from a camera and displays them on the screen (uses one big XAML island in a windows forms window). After running it for a few hours it often crashes with an "Object reference not set to an instance of an object" exception that I can catch in the AppDomain UnhandledException event handler. I can get the following stack trace:
System.Runtime.CompilerServices.AsyncVoidMethodBuilder.NotifySynchronizationContextOfCompletion()
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__139_1(Object state)
at System.Threading.QueueUserWorkItemCallbackDefaultContext.Execute()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Unfortunately, all my efforts to find the cause of this exception have been unsuccessful. None of the code that I run on the thread pool (one periodic timer and some code to process the image frame) seems to be active when it occurs.
Configuration
Windows 10, version 2004
x64
.net core SDK 3.1.400
That's the entirety of the stack trace? You have an async void method somewhere that is experiencing an unhandled null reference exception, which is then by design propagated on a thread pool thread to crash the process.
Yes, this is entire stacktrace or what I can get from the StackTrace poperty of the exception. Is there any way to find out where in my code it is actually originating from?
I just wanted to add some additional information here because I have found a way around this issue. Previously, my code looked something like this (async void method called on the UI thread when an image is ready to be drawn):
...
await SwitchToBackgroundThread();try{Draw and present image using win2d
}catch(){}awaitSwitchToUIThread();...
The thread switching methods are based on the approach from this article, calling ThreadPool.RunAsync() and SynchronizationContext.Post() (context from the UI thread). I have now changed to code not to switch to a background thread and this seems avoid all crashes. However, I still do not know what is going wrong with the code shown above, I can only say that the crashes are a lot more frequent on a slower machine.
This is the implementation of the related classes:
publicstructSynchronizationContextSwitcher:INotifyCompletion{privatestaticreadonlySendOrPostCallback_postCallback= state =>((Action)state)();privatereadonlySynchronizationContext_context;publicSynchronizationContextSwitcher(SynchronizationContextcontext){_context=context;}publicSynchronizationContextSwitcherGetAwaiter()=>this;publicboolIsCompleted=>_context==SynchronizationContext.Current;publicvoidOnCompleted(Actioncontinuation)=>_context.Post(_postCallback,continuation);publicvoidGetResult(){}}publicstructThreadPoolThreadSwitcher:INotifyCompletion{publicThreadPoolThreadSwitcherGetAwaiter()=>this;publicboolIsCompleted=>SynchronizationContext.Current==null;publicvoidGetResult(){}publicvoidOnCompleted(Actioncontinuation)=>_=Windows.System.Threading.ThreadPool.RunAsync(_ =>continuation());}publicclassThreadSwitcher{staticSynchronizationContext_uiContext=null;staticpublicvoidSetAsUIThread(){_uiContext=SynchronizationContext.Current;}staticpublicSynchronizationContextSwitcherSwitchToUIThread(){returnnewSynchronizationContextSwitcher(_uiContext);}staticpublicThreadPoolThreadSwitcherSwitchToBackgroundThread(){returnnewThreadPoolThreadSwitcher();}}
My guess is that you're somehow ending up with a null SynchronizationContext.Current, and that's causing the _context.Post call in your OnCompleted method to null ref. You might try adding an assert there to help prove or disprove that. You could also try hooking up an event handler for AppContext.FirstChanceException (and filtering down to just NullReferenceException) to see if Environment.StackTrace during that handler's invocation gives you a better sense of where it's coming from.
This is the stacktrace that I could gather with the FirstChanceException:
at MyApp.Program.CurrentDomain_FirstChanceException(Object sender, FirstChanceExceptionEventArgs fe) in C:\...:line 69
at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.NotifySynchronizationContextOfCompletion()
at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()
at MyApp.XAML_UI.CameraOutputControl.UpdateImage(PictureObjectInfo newPicture) in C:\...:line 507
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AsyncStateMachineBox`1.MoveNext(Thread threadPoolThread)
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
Line 507 is the last line of the UpdateImage() method (the closing brace).
Thanks. And that's for a null reference exception? Is this in debug or release? Can you break into the app in this first chance handler in a debugger and share details of the state of things, e.g. in the NotifySynchronizationContextOfCompletion method, what is the value for the _synchronizationContext field? (Or grab a dump from within that handler and share it with me?)
Yes, it is a null reference exception. I could not observe the crash in debug builds and when using a release build, all the fields are reported to have been optimized out. Just to add some more information (not sure if helpful): The UpdateImage() method is the handler for a Progress object and constructed on the UI thread (SynchronizationContext.Current reports "WindowsFormsSynchronizationContext", same as in the FirstChanceException handler). A dedicated background thread uses the OnReported() method to call it.
@tarekgh Looking at the documentation, it seems that time travel debugging might not be suitable for this case as the application needs to run for a few hours before encountering the crash?
At this point, there's not really anything actionable we can do. If you're able to set up a simple runnable repro you can share, we'd be happy to take another look. In the meantime, I'm going to close this. Thanks.
Activity
Dotnet-GitSync-Bot commentedon Aug 6, 2020
I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.
stephentoub commentedon Aug 6, 2020
That's the entirety of the stack trace? You have an async void method somewhere that is experiencing an unhandled null reference exception, which is then by design propagated on a thread pool thread to crash the process.
lhak commentedon Aug 8, 2020
Yes, this is entire stacktrace or what I can get from the StackTrace poperty of the exception. Is there any way to find out where in my code it is actually originating from?
lhak commentedon Aug 31, 2020
I just wanted to add some additional information here because I have found a way around this issue. Previously, my code looked something like this (async void method called on the UI thread when an image is ready to be drawn):
The thread switching methods are based on the approach from this article, calling ThreadPool.RunAsync() and SynchronizationContext.Post() (context from the UI thread). I have now changed to code not to switch to a background thread and this seems avoid all crashes. However, I still do not know what is going wrong with the code shown above, I can only say that the crashes are a lot more frequent on a slower machine.
stephentoub commentedon Sep 16, 2020
What is the implementation of your SwitchToBackgroundThread and SwitchToUIThread method?
lhak commentedon Sep 23, 2020
This is the implementation of the related classes:
stephentoub commentedon Sep 23, 2020
My guess is that you're somehow ending up with a null
SynchronizationContext.Current, and that's causing the_context.Postcall in yourOnCompletedmethod to null ref. You might try adding an assert there to help prove or disprove that. You could also try hooking up an event handler forAppContext.FirstChanceException(and filtering down to just NullReferenceException) to see ifEnvironment.StackTraceduring that handler's invocation gives you a better sense of where it's coming from.lhak commentedon Sep 30, 2020
This is the stacktrace that I could gather with the FirstChanceException:
Line 507 is the last line of the UpdateImage() method (the closing brace).
stephentoub commentedon Sep 30, 2020
Thanks. And that's for a null reference exception? Is this in debug or release? Can you break into the app in this first chance handler in a debugger and share details of the state of things, e.g. in the NotifySynchronizationContextOfCompletion method, what is the value for the _synchronizationContext field? (Or grab a dump from within that handler and share it with me?)
lhak commentedon Oct 2, 2020
Yes, it is a null reference exception. I could not observe the crash in debug builds and when using a release build, all the fields are reported to have been optimized out. Just to add some more information (not sure if helpful): The UpdateImage() method is the handler for a Progress object and constructed on the UI thread (SynchronizationContext.Current reports "WindowsFormsSynchronizationContext", same as in the FirstChanceException handler). A dedicated background thread uses the OnReported() method to call it.
tarekgh commentedon Oct 2, 2020
@lhak if you can easy repro it in your environment, is it possible you can collect Time Travel Debugging Dump and share it?
lhak commentedon Oct 7, 2020
@tarekgh Looking at the documentation, it seems that time travel debugging might not be suitable for this case as the application needs to run for a few hours before encountering the crash?
stephentoub commentedon Jan 21, 2023
At this point, there's not really anything actionable we can do. If you're able to set up a simple runnable repro you can share, we'd be happy to take another look. In the meantime, I'm going to close this. Thanks.