18

I have a C# application which is hitting an ObjectDisposedException with the message

Safe handle has been closed

This happens as soon as I launch the application.

Sadly the stack trace is really unhelpful (see below). Is there any way for me to determine what call was being attempted asynchronously here?

Does DoAsyncCall() really imply an async method call?

mscorlib.dll!System.Threading.EventWaitHandle.Set() + 0xe bytes
mscorlib.dll!System.Runtime.Remoting.Messaging.AsyncResult.SyncProcessMessage(System.Runtime.Remoting.Messaging.IMessage msg) + 0x12f bytes
mscorlib.dll!System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(System.Runtime.Remoting.Messaging.IMessage msg, System.Runtime.Remoting.Messaging.IMessageSink replySink = {System.Runtime.Remoting.Messaging.AsyncResult}) + 0x279 bytes
mscorlib.dll!System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.DoAsyncCall() + 0x32 bytes mscorlib.dll!System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.ThreadPoolCallBack(object o) + 0x28 bytes
mscorlib.dll!System.Threading._ThreadPoolWaitCallback.WaitCallback_Context(object state) + 0x2f bytes
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x6f bytes
mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(System.Threading._ThreadPoolWaitCallback tpWaitCallBack) + 0x53 bytes
mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(object state) + 0x59 bytes

HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
mchr
  • 6,161
  • 6
  • 52
  • 74

3 Answers3

17

You are disposing something which is still being used by a different thread.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Thanks for this - is there any way to work out what I am disposing and what other thread is still using it? – mchr Dec 17 '10 at 17:57
  • 5
    @mchr: Debug, Break At Function, `System.Runtime.InteropServices.SafeHandle.Dispose`. – SLaks Dec 17 '10 at 17:58
17

The problem was caused by my use of a using(){} block.

    using (WaitHandle handle = asyncResponse.AsyncWaitHandle)
    {
      asyncResponse.AsyncWaitHandle.WaitOne();
      string response = asyncRequest.EndInvoke(asyncResponse);
      asyncResponse.AsyncWaitHandle.Close();
      return response;
    } 

When the calling thread is interrupted the using block is still calling Close on the WaitHandle.

mchr
  • 6,161
  • 6
  • 52
  • 74
0

Goofing around with security on API, and misspelled "Users":

[Authorize(Roles = "User")] // exception...

ObjectDisposedException: Safe handle has been closed

Should have been:

[Authorize(Roles = "Users")] // works!

A different error is thrown when group does not exist, like:

[Authorize(Roles = "SomeGroupThatDoesNotExist")]

Win32Exception: The trust relationship between the primary domain and the trusted domain failed

Adam Cox
  • 3,341
  • 1
  • 36
  • 46