Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObjectDisposedException - DangerousAddRef

I got a somehow complex .net console application, that uses WPF for some notification windows and also does some http calls. In very rare cases, that application crashes and the only error message I'm able to get comes from windows event viewer:

Application: xyz.exe
Description: The process was terminated due to an unhandled exception.
Exception Info: System.ObjectDisposedException
Stack:
   at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean ByRef)
   at Microsoft.Win32.Win32Native.SetEvent(Microsoft.Win32.SafeHandles.SafeWaitHandle)
   at System.Threading.TimerQueueTimer.Fire()
   at System.Threading.TimerQueue.FireNextTimers()

I have no idea where the stack trace comes from. Any ideas where to look for this issue? Here are some of my thoughts:

  • Since there is this timer stuff on the stack, could it be related to System.Threading.Timer? Because there are some timers used in code?

  • There is also some http communication involved (httpclient, httpwebrequest) which is using timeouts. Could there be a connection to this error?

Sorry for the very unspecific question, but I'm totally stuck here and just need some kind of starting point.

like image 459
DanielG Avatar asked Dec 19 '25 05:12

DanielG


1 Answers

I had the same problem and find out that the following code cause the exception:

using (ManualResetEvent resetEvent = new ManualResetEvent(false))
{
    timer.Dispose(resetEvent);
    resetEvent.WaitOne(1000);
}

In case when the timer is not disposed within a second the exception may occurred. The solution is - to dispose the resetEvent only if the WaitOne method returns true.

like image 68
begemot Avatar answered Dec 20 '25 18:12

begemot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!