To find which operation is blocking the context switch and causing the contextSwitchDeadlock MDA to be displayed, you can use the following steps. Note that I will be referring to Visual Studio 2012.
- Reproduce the error. This could involve some trial and error.
- Click 'OK' rather than 'Continue' in the Managed Debugging assistant which is displayed.
- Ensure that the Debug Location toolbar is active by right clicking on the toolbar docking region and selecting 'Debug Location'. You should see a drop down list labelled 'Thread' in the toolbar if it is active.
- The selected item in the Thread drop down list should be a thread other than the main thread as it will be a background thread that is complaining that the main thread is hogging all of the attention. Select the main thread in the drop down list.
- You should now see the code that is blocking the context switch in the code editor.
Assuming that you decide against moving the resource intensive operation off your main thread - take a look at some of the other answers and comments here before you do - you have the following options to disable the Managed Debugging Assistants.
Within the Visual Studio Debugger
- You can disable an MDA directly in the MDA dialog that is
displayed when the error occurs by unchecking 'Break when this
exception type is thrown'.
- With Exception Settings dialog using the instructions below from MSDN.
...on the Debug menu, click Exceptions. (If the Debug menu does not contain an Exceptions command, click Customize on the Tools menu to add it.) In the Exceptions dialog box, expand the Managed Debugging Assistants list, and then clear the Thrown check box for the individual MDA.
Outside the Visual Studio Debugger
- Registry Key (Machine Wide, All MDAs affected)
- Environment Variable (Machine Wide, MDAs can be specified)
- Application Configuration Settings (Application scope, MDAs can be specified)
Note: One of the first two options must be set to 1 for the third to have any effect.
In my case, the problem was a call to ObjectContext.SaveChanges() in the Entity Framework within a console application. With the MTAThreadAttribute applied to the Main()
method the ContextSwitchDeadlock exception was no longer raised. I am unfortunately unsure of the full affects of this change.