justcoding121 / windows-user-action-hook

A .NET library to subscribe for Windows operating system global user actions such mouse, keyboard, clipboard & print events

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ContextSwitchDeadlock in hosted environment

retailcoder opened this issue · comments

My app is a COM add-in for the VBE - it's basically hosted in a host (the VBE) that's itself hosted in a host (the VBA host app)... and add another host layer to that when I'm running it in the VS debugger.

Long story short, everything seems to work when I'm running in the VS debugger. But when it isn't (i.e. I just launch Excel and load the last build), bringing up the VBA editor stalls the Office host app, and one of my contributors has reported seeing this error message:

ContextSwitchDeadlock occurred
Message: Managed Debugging Assistant 'ContextSwitchDeadlock' has detected a problem in 'C:\Program Files (x86)\Microsoft Office\root\Office16\EXCEL.EXE'.
Additional information: The CLR has been unable to transition from COM context 0xfc79c8 to COM context 0xfc7910 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations.

I suspect I might need to somehow pass the VBE MainWindow's hWnd to the EventHook API, but can't be sure.

I don't understand why it works when the VS debugger is attached, and deadlocks when it isn't (actually that Managed Debugging Assistant message seems to imply a debugger was attached), but I've disabled all other hooks and the issue persists as long as I have EventHook hooks attached; the issue resolves itself if I instead disabled the EventHook hooks and leave mine (I have a TimerHook regularly checking if the VBE is the active window, and a Hotkey hook listening for WM_HOTKEY messages sent) - so I know for a fact that the problem is with EventHook hooks.