Skip to content

Object reference not set to an instance of an object exception in NotifySynchronizationContextOfCompletion() #40463

Closed

Description

@lhak

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

Activity

  1. Dotnet-GitSync-Bot commented on Aug 6, 2020

    @Dotnet-GitSync-Bot
    Collaborator

    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.

  2. added
    untriaged
    on Aug 6, 2020
  3. stephentoub commented on Aug 6, 2020

    @stephentoub
    Member

    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.

  4. added
    question
    on Aug 7, 2020
  5. removed
    untriaged
    on Aug 7, 2020
  6. added this to the Future milestone on Aug 7, 2020
  7. lhak commented on Aug 8, 2020

    @lhak
    Author

    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?

  8. lhak commented on Aug 31, 2020

    @lhak
    Author

    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()
    {
    }
    await SwitchToUIThread();
    ...

    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.

  9. stephentoub commented on Sep 16, 2020

    @stephentoub
    Member

    What is the implementation of your SwitchToBackgroundThread and SwitchToUIThread method?

  10. lhak commented on Sep 23, 2020

    @lhak
    Author

    This is the implementation of the related classes:

    	public struct SynchronizationContextSwitcher : INotifyCompletion
    	{
    		private static readonly SendOrPostCallback _postCallback = state => ((Action)state)();
    
    		private readonly SynchronizationContext _context;
    		public SynchronizationContextSwitcher(SynchronizationContext context)
    		{
    			_context = context;
    		}
    
    		public SynchronizationContextSwitcher GetAwaiter() => this;
    
    		public bool IsCompleted => _context == SynchronizationContext.Current;
    
    		public void OnCompleted(Action continuation) => _context.Post(_postCallback, continuation);
    
    		public void GetResult() { }
    	}
    
    	public struct ThreadPoolThreadSwitcher : INotifyCompletion
    	{
    		public ThreadPoolThreadSwitcher GetAwaiter() => this;
    		public bool IsCompleted => SynchronizationContext.Current == null;
    		public void GetResult() { }
    		public void OnCompleted(Action continuation) => _ = Windows.System.Threading.ThreadPool.RunAsync(_ => continuation());
    	}
    
    
    	public class ThreadSwitcher
    	{
    		static SynchronizationContext _uiContext = null;
    
    		static public void SetAsUIThread()
    		{
    			_uiContext = SynchronizationContext.Current;
    		}
    
    		static public SynchronizationContextSwitcher SwitchToUIThread()
    		{
    			return new SynchronizationContextSwitcher(_uiContext);
    		}
    
    		static public ThreadPoolThreadSwitcher SwitchToBackgroundThread()
    		{
    			return new ThreadPoolThreadSwitcher();
    		}
    	}
  11. stephentoub commented on Sep 23, 2020

    @stephentoub
    Member

    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.

  12. lhak commented on Sep 30, 2020

    @lhak
    Author

    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).

  13. stephentoub commented on Sep 30, 2020

    @stephentoub
    Member

    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?)

  14. lhak commented on Oct 2, 2020

    @lhak
    Author

    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.

  15. tarekgh commented on Oct 2, 2020

    @tarekgh
    Member

    @lhak if you can easy repro it in your environment, is it possible you can collect Time Travel Debugging Dump and share it?

  16. lhak commented on Oct 7, 2020

    @lhak
    Author

    @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?

  17. stephentoub commented on Jan 21, 2023

    @stephentoub
    Member

    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.

  18. ghost locked as resolved and limited conversation to collaborators on Feb 21, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Threading.Tasksquestion

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions