Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solve DisconnectedContext in Visual Studio

I always got a DisconnectedContext (a managed debugging assistant) when I run my application using Visual Studio. Given Google and docs, this can happen when COM objects on STA are called from other thread.

However, when I look throught all the threads when the popup appears, I don't find anything like this. (And I don't find anything weird at all).

Some ideas on how I can find the way the DisconnectedContext is raised?

like image 215
Toto Avatar asked Feb 01 '11 09:02

Toto


2 Answers

Found this while looking for the same answer, thought I'd add a comment...

This error is virtually unavoidable in any multi-threaded app using CLR objects through in-process interop (on transient threads). The problem is that the CLR had non-deterministic cleanup of objects (which may be RCW's, with thread-affinity on the underlying COM objects). There's no way you can tell the runtime to clean up objects created on a thread (at least without creating another non-deterministic cleanup handle on the thread); it's a design limitation of the interop mechanism. Given that, there's no way to ever safely exit a thread which has created any CLR objects without potentially getting this error.

Best advice: don't use CLR/interop if you can help it. Next best advice: use COM+ to process-isolate your interop, so the CLR can live in a process which never terminates threads (use persistent thread pool or equivalent). Next best advice: join me in continuing to tell Microsoft about this design-level problem with their interop, and hope they fix it.

like image 97
Nick Avatar answered Oct 24 '22 02:10

Nick


This is a pretty serious warning, don't ignore it. The scenario is that you created a COM object on a thread and that thread exited. But you keep using that object. COM takes care of objects that announced themselves to be not thread-safe (aka apartment threaded), it automatically marshals any calls on that object to the thread that created it. That can't work when that thread is no longer around.

Ignoring the warning can produce occasional and very hard to troubleshoot threading race errors. Stuff that goes subtly wrong only once a week. Review your code, pay attention to how the object that it complains about got created.

like image 4
Hans Passant Avatar answered Oct 24 '22 03:10

Hans Passant