.NET - ContextSwitchDeadlock was detected

孤者浪人 提交于 2019-11-27 02:09:40

问题


i have a class in c# (.net 3.5 cp, vs2010) which executes complex comuptations which ussually take a long time. After a minute there is thrown an exception, that ContextSwitchDeadlock was detected. Exception is localised, to my non english language so i cant copy paste, but meaning is following: ¨ CLR module could not transition from context COM ... to context COM ... for 60 seconds. Subproces which owns target context/apartment is probably doing a non-pumping wait or processing a very long running operation without pumping Windows system messages.

Basicaly, it looks like my application is computing and not responding to windows for a long time and visual studio shuts it down and reports problable deadlock.

I was trying to do some research and found two solutions:

  1. Disable some option in visual studio debbuger to detect deadlocks. Dost not work for me because it woirks only for debugging purposes.

  2. Call some DoEvents method, but it was for windows forms and not WPF and i am using WPF.

There was also suggestion to create separate thread, but i am complete new to threading and dont know what should i do. Any suggestions please?


回答1:


It is just a warning from a Managed Debugging Assistant (MDA). Your code is violating a pretty hard requirement for Single Threaded Apartment (STA) threads, they are not allowed to block for long periods. The warning is real enough, blocking the UI thread can easily cause deadlock. But the explanation in your case is simple, it just goes catatonic because it is busy computing, not because it actually blocked. The MDA can't tell the difference.

You can turn off the warning with Debug + Exceptions, open the Managed Debugging Assistants node and untick ContextSwitchDeadlock.

That still leaves the user with a window on her desktop that is dead to the world, not exactly a great user experience. And it can have side-effects, causing other programs to become unresponsive when they send messages to toplevel windows.

You do need to use threading to really solve this problem. Have a look at BackgroundWorker, it is well documented in the MSDN Library and many other places.



来源:https://stackoverflow.com/questions/8106159/net-contextswitchdeadlock-was-detected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!