When using Visual Studio 2005 development tools, if we have a large amount of data for processing, such as writing more than 30 thousand pieces of data into excel, We can frequently read and write the database, an error message may appear:
"Contextswitchdeadlock was detected" error message popping up when debugging.
The CLR has been unable to transition from com context 0x197060 to com context 0x196ef0 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 shocould use pumping wait primitives (such as cowaitformultiplehandles) and routinely pump messages during long running operations.
The solution is to remove the contextswitchdeadlock in debug> exceptions> managed debug assistants.
If the Code does not operate on COM objects, this is a very simple and effective method.
However, if our code really has operations on COM objects, such as writing to excel, is there a deadlock exception and will cause code crash in the future? In this case, we can set a counter. For example, for every 100 pieces of data written, we can proceed with the application. the doevents () operation is used to notify the main thread that a certain operation is too long, instead of a deadlock in our code.