Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

c# - .NET - ContextSwitchDeadlock was detected

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...