ContextSwitchDeadlock when running unit (integration) tests - c#

We get the following error when running at test:
ContextSwitchDeadlock was detected
Message: The CLR has been unable to transition from COM context 0x344b0c0 to COM
context 0x344b230 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.
The test does a WCF call to a method on the service layer that gets data from the database using Entity Framework. Data is also Cached on the server side using EntLib Caching Application Block.
The test that tests the same code on the server side passes without error.

Found the problem.
We were not closing the WCF proxies correctly. We were using "using" instead of a try catch with close or abort.
Therefore, an error in one test would cause a ContextSwitchDeadlock in a subsequent test that tried to use the same WCF service.

Related

CustomXMLParts.Add slow due to ContextSwitchDeadlock

I'm getting a
ContextSwitchDeadlock
when adding a CustomXMLPart after performing a Documents.Add().
The same code was working fine last week..
I understand that ContextSwitchDeadlock is caused by a long running operation (this is not a duplicate question).
Why would the CustomXMLParts.Add() command result in a long running operation?
Anyone come across this? and any ideas how to troubleshoot?
ContextSwitchDeadlock occurred Message: Managed Debugging Assistant
'ContextSwitchDeadlock' has detected a problem in 'C:\Program Files
(x86)\Microsoft Office\root\Office16\WINWORD.EXE'. Additional
information: The CLR has been unable to transition from COM context
0xfdb520 to COM context 0xfdb468 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.
The context switch deadlock can show up when debugging a long running process. For the most part you can ignore it if the process is expected to be long running.
see previous stackoverflow answer

How to recover after ThreadAbortException?

I have several long-running threads in an MVC3 application that are meant to run forever.
I'm running into a problem where a ThreadAbortException is being called by some other code (not mine) and I need to recover from this gracefully and restart the thread. Right now, our only recourse is to recycle the worker process for the appDomain, which is far from ideal.
Here's some details about this code works:
A singleton service class exists for this MVC3 application. It has to be a singleton because it caches data. This service is responsible for making request to a database. A 3rd party library is used for the actual database connection code.
In this singleton class we use a collection of classes that are called "QueryRequestors". These classes identify unique package+stored_procedure names for requests to the database, so that we can queue those calls. That is the purpose of the QueryRequestor class: to make sure calls to the same package+stored_procedure (although they may have infinite different parameters) are queued, and do not happen simultaneously. This eases our database strain considerably and improves performance.
The QueryRequestor class uses an internal BlockingCollection and an internal Task (thread) to monitor its queue (blocking collection). When a request comes into the singleton service, it finds the correct QueryRequestor class via the package+stored_procedure name, and it hands the query over to that class. The query gets put in the queue (blocking collection). The QueryRequestor's Task sees there's a request in the queue and makes a call to the database (now the 3rd party library is involved). When the results come back they are cached in the singleton service. The Task continues processing requests until the blocking collection is empty, and then it waits.
Once a QueryRequestor is created and up and running, we never want it to die. Requests come in to this service 24/7 every few minutes. If the cache in the service has data, we use it. When data is stale, the very next request gets queued (and subsequent simultaneous requests continue to use the cache, because they know someone (another thread) is already making a queued request, and this is efficient).
So the issue here is what to do when the Task inside a QueryRequestor class encounters a ThreadAbortException. Ideally I'd like to recover from that and restart the thread. Or, at the very least, dispose of the QueryRequestor (it's in a "broken" state now as far as I'm concerned) and start over. Because the next request that matches the package+stored_procedure name will create a new QueryRequestor if one is not present in the service.
I suspect the thread is being killed by the 3rd party library, but I can't be certain. All I know is that nowhere do I abort or attempt to kill the thread/task. I want it to run forever. But clearly we have to have code in place for this exception. It's very annoying when the service bombs because a thread has been aborted.
What is the best way to handle this? How can we handle this gracefully?
You can stop re-throwing of ThreadAbortException by calling Thread.ResetAbort.
Note that most common case of the exception is Redirect call, and canceling thread abort may case undesired effects of execution of request code that otherwise would be ignored due to killing the thread. It is common issue in WinForms (where separation of code and rendering is less clear) than in MVC (where you can return special redirect results from controllers).
Here's what I came up with for a solution, and it works quite nicely.
The real issue here isn't preventing the ThreadAbortException, because you can't prevent it anyway, and we don't want to prevent it. It's actually a good thing if we get an error report telling us this happened. We just don't want our app coming down because of it.
So, what we really needed was a graceful way to handle this Exception without bringing down the application.
The solution I came up with was to create a bool flag property on the QueryRequestor class called "IsValid". This property is set to true in the constructor of the class.
In the DoWork() call that is run on the separate thread in the QueryRequestor class, we catch the ThreadAbortException and we set this flag to FALSE. Now we can tell other code that this class is in an Invalid (broken) state and not to use it.
So now, the singleton service that makes use of this QueryRequestor class knows to check for this IsValid property. If it's not valid, it replaces the QueryRequestor with a new one, and life moves on. The application doesn't crash and the broken QueryRequestor is thrown away, replaced with a new version that can do the job.
In testing, this worked quite well. I would intentionally call Thread.Abort() on the DoWork() thread, and watch the Debug window for output lines. The app would report that the thread had been aborted, and then the singleton service was correctly replacing the QueryRequestor. The replacement was then able to successfully handle the request.

CLR has been unable to transition from COM context 0x3b2d70 to COM context

While debugging an application i am getting the following error.
The CLR has been unable to transition from COM context 0x3b2d70 to COM
context 0x3b2ee0 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.
Why system throws this error.
I got the solution
Need to uncheck ContextSwitchDeadlock under Debug->Exceptions->Managed Debugging Assistants.
After unchecking ContextSwitchDeadlock its not throwing the error.

Error on inserting data in SQL Server db from Excel Sheet

I am inserting data from an Excel sheet to SQL Server 2005 db. I am getting this error randomly, sometimes after 20-30 records and sometimes after 1000s. I am unable to find the reason.
I am using Visual Studio 2008.
The CLR has been unable to transition
from COM context 0x21a7b0 to COM
context 0x21a920 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.
Can anybody tell me what this error is and why I am getting this.
Thanks.
edit: This thread seems to directly answer your question and the steps involved to solve it.
If you want to learn more check out this MSDN article.
Are you closing connections when you are done with them? It may be that connections are left open, consuming the maximum number of connections available to your application, and eventually timing out.

Strange Message about threads in C#

I have a program that I run and in the middle I get this message:
Managed Debugging Assistant 'ContextSwitchDeadlock' has detected a problem in 'C:\Documents and Settings\Lena G\My Documents\SchoolStuff\IR Information\Home Work\FianlProject\finalProject\finalProject\bin\Debug\finalProject.vshost.exe'.
Additional Information: The CLR has been unable to transition from COM context 0x3407968 to COM context 0x3407ad8 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.
I understand that it has something to do with the fact that it runs for 60 seconds without stopping or something like that? How is it a problem?
I also put [STAThread] before the main of my program because if I remove it then it shows me this message:
An unhandled exception of type 'System.Threading.ThreadStateException' occurred in System.Windows.Forms.dll
Additional information: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process.
Anyone know how I can solve this problem?
Thanks in advance,
Lena
You need to make sure that your thread that owns the COM component isn't being "locked up" via processing for >60 seconds.
What's probably happening is that you have a COM object in a form, and you're doing work on the UI thread. If your UI gets blocked by the processing for >60 seconds, the COM component can complain.
Consider using a BackgroundWorker instance to handle your long running process. This would push the work onto a background thread, and allow the COM component to process messages without complaints.
It is a warning that's generated when you make calls on an ActiveX object from a background thread and your main thread is blocked. Perhaps more likely: there was a bug in the retail version of Visual Studio 2005 that tripped this warning for no good reason. It got fixed in Service Pack 1, be sure you have that installed. Yet another workaround is to shut it up. Debug + Exceptions, Managed Debugging Assistants, untick the ContextSwitchDeadlock warning. But use SP1 if you don't have it.

Categories

Resources