C# – Visual Studio: ContextSwitchDeadlock

csql servervisual studio

I have been getting an error message that I can't resolve. It originates from Visual Studio or the debugger. I'm not sure whether the ultimate error condition is in VS, the debugger, my program, or the database.

This is a Windows app. Not a web app.

First message from VS is a popup box saying:
"No symbols are loaded for any call stack frame. The source code can not be displayed."
When that is clicked away, I get:
"ContextSwitchDeadlock was detected", along with a long message reproduced below.

The error arises in a loop that scans down a DataTable. For each line, it uses a key (HIC #) value from the table as a parameter for a SqlCommand. The command is used to create a SqlDataReader which returns one line. Data are compared. If an error is detected a row is added to a second DataTable.

The error seems to be related to how long the procedure takes to run (i.e. after 60 sec), not how many errors are found. I don't think it's a memory issue. No variables are declared within the loop. The only objects that are created are the SqlDataReaders, and they are in Using structures. Add System.GC.Collect() had no effect.

The db is a SqlServer site on the same laptop.

There are no fancy gizmos or gadgets on the Form.

I am not aware of anything in this proc which is greatly different from what I've done dozens of times before. I have seen the error before, but never on a consistent basis.

Any ideas, anyone?

Full error Text:
The CLR has been unable to transition from COM context 0x1a0b88 to COM context 0x1a0cf8 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.

Best Answer

The ContextSwitchDeadlock doesn't necessarily mean your code has an issue, just that there is a potential. If you go to Debug > Exceptions in the menu and expand the Managed Debugging Assistants, you will find ContextSwitchDeadlock is enabled.

If you disable this, VS will no longer warn you when items are taking a long time to process. In some cases you may validly have a long-running operation. It's also helpful if you are debugging and have stopped on a line while this is processing - you don't want it to complain before you've had a chance to dig into an issue.