Handling executing processes - c#

A couple of days ago I began to get an error with a c# winform application I've been creating stating that
The CLR has been unable to transition from COM context 0x278f58 to COM context 0x2790c8 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 is occuring when I am using a separate thread to run exe processes to avoid freezing up the ui. In a release version, this program runs fine and as expected but pretty much makes it impossible to consistently debug my program (sometimes works fine, others not so fine)..
I've tried implementing this process by forcing a BackgroundWorker to be synchronous using multiple googled answers which solves the issue of this error but makes my program work in unexpected ways (textboxes populated before exe finished resulting in erroneous data).
I have read that this error will only occur in production and not in a release.. so my question is should I just try to live with this annoyance or is their a non backgroundworker solution? If any code example is needed I can provide but I don't believe it is necessary

The Managed Debugging Assistant (MDA) is telling you that a single-threaded apartment (STA) COM thread hasn't responded to a message in 60 seconds. STA COM is done through message passing. This exception occurs if MDA is switched on, which it is by default when running under a debugger. The MDA works to detect deadlock with a pre-defined timeout, and it's only effective when you're running the program under the VS debugger.
Since many COM components are STA and the main thread in Windows Forms is also STA, this is a warning that you’re blocking. This is probably occurring because you are stalling the message loop by spending time stepping through code.
To switch this off for a single project, add the following content to your application configuration file:
<mdaConfig>
<assistants>
<contextSwitchDeadlock enable="false" />
</assistants>
</mdaConfig>
To switch this off globally:
Click on the Debug menu in Visual Studio.
Choose the Exceptions option (Debug -> Exceptions).
The Exceptions window will open.
Expand the "Managed Debugging Assistants" node.
Uncheck the ContextSwitchDeadlock option under the Thrown column.
Click OK and close the Exceptions window.
The implication of disabling this MDA is that you lose a useful tool for discovering bugs before you release the application. Of course if you see this deadlock when not running under the debugger then you need to do a normal deadlock analysis.

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

Process continues running after main thread has terminated?

I'll start by saying I do not have a lot of experience in troubleshooting multi-threading problems. So a lot of what I've read about debugging race conditions, dead locks, live locks, etc. are strictly theoretical to me.
I have this .NET application that is making use of a dynamically loaded native win32 dll. If the dll is never loaded the application terminates without a problem. However, if the dll is loaded then when the user exits the application the UI disappears but the process never terminates.
I've turned on native code debugging in the project settings so I can see all the threads that are running. When the user closes the application window the main thread appears to terminate. I know this because if I perform a Break All in the Threads windows in Visual Studio the main thread is re-categorized as a worker thread and there is no call stack available for it. There are 20 other threads still active, all with call stacks. I've looked through the call stacks for all of these threads and nothing sticks out at me (there's no mention of the dll in any of the call stacks).
What steps can I take to narrow down the cause of this problem? Are there any additional tools I should be using to help pin point the problem?
This means that some of your Foreground Threads are still alive. Unlike Background Threads, Foreground Threads keeps the process alive.
You should either use Background Threads or Stop your Foregrounds Threads to be able to exit the process gracefully.
Windows application will automatically exit when all of its thread(s) are stopped.
As you said
If the dll is never loaded the application terminates without a
problem
I'm assuming all the running threads are unmanaged threads(not created by clr). There is no concept of background threads in native code. All threads must be terminated to terminate the process.
You must find a way to signal all threads to exit in that library. See if you have any api exposed for that.
If you don't find anything, you've got a "Sledge Hammer" approach. i.e Terminate the process with Environment.Exit which works almost always. Be sure you use this approach as a last resort as this can corrupt the process state.

How to capture information on why my application is "hung"

I have a WPF monitoring application that uses a separate (internally developed) C# test
infrastructure to execute tests and monitor and log the results. I also uses a commercial package (InGear) to communicate to a PLC. As a result, the application has LOTS of threads (most of which are created by the tools I am using).
Because of the nature of the environment, it would be very difficult to use a debugger in the target environment; so, we are both using log4net to log diagnostics.
I use try/catch blocks in around my external calls and also have setup a unhandled exception handlers both at the WPF and AppDomain levels.
During our first long run the application appears to have become non-responsive and I got the standard "not responding" dialog. Looking at the log it seems like everything just stopped. Ex: I can see from the log that a DispatcherTimer was set to respond on the main thread in 1 sec; but, never did.
So.... My questions are:
How can I detect the hang or is hook into Window's detection that I am hung? Note that I am assuming that it could be a higher priority thread that is blocking my UI tread; so, I probably can't respond to a Windows Message.
Once I do tap in, how do I find out what thread is the culprit. Being able the log its call stack would be a big plus.
Maybe simplistic, but what about attaching the debugger to the process, doing a 'Break All' and then inspect the stack trace of the various threads?
Where I was unable to determine a way to detect the 'hang' before Windows does, I was able to catch the Windows timeout exception and ultimately traced the problem to unmanaged code in the Oracle .NET component.

Application doesn't exit with 0 threads

We have a WinForms desktop application, which is heavily multithreaded. 3 threads run with Application.Run and a bunch of other background worker threads. Getting all the threads to shut down properly was kind of tricky, but I thought I finally got it right.
But when we actually deployed the application, users started experiencing the application not exiting. There's a System.Threading.Mutex to prevent them from running the app multiple times, so they have to go into task manager and kill the old one before they can run it again.
Every thread gets a Thread.Join before the main thread exits, and I added logging to each thread I spawn. According to the log, every single thread that starts also exits, and the main thread also exits. Even stranger, running SysInternals ProcessExplorer show all the threads disappear when the application exits. As in, there are 0 threads (managed or unmanaged), but the process is still running.
I can't reproduce this on any developers computers or our test environment, and so far I've only seen it happen on Windows XP (not Vista or Windows 7 or any Windows Server). How can a process keep running with 0 threads?
Edit:
Here's a bit more detail. One of event loops is hosting an Win32 interop DLL which uses a COM object to talk to a device driver. I put it in its own thread because the device driver is time sensitive, and whenever the UI thread would block for a significant amount of time (such as waiting for a database call to finish), it would interfere with the device driver.
So I changed the code so the main thread would do a Thread.Join with the device driver thread. That actually caused the application to lock up... it logs a few more calls on the UI thread after the Join completed and then everything stops. If the device is powered off, the driver never starts, and the problem goes away. So it looks like the driver must be responsible for keeping the application alive, even after it's supposedly been shut down.
When you create your threads, set IsBackground=true on them. When your main ui thread/app is closed, all created threads will automatically be shut down.
http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx
Is it possible that the children of your Application.Run calls aren't terminating? Also, what's actually causing the application to exit - does it automatically close when all the threads have terminated (automatically meaning you wrote some code to do that), or is it user-imitated?
I had an issue once where there was a race condition in my "thread complete" event code that would sometimes result in what you're seeing. The last two threads would finish at the same time, fire the event simultaneously, and each event would decide it wasn't the last thread, so the application would continue running, even though the thread count was zero. To resolve this, I was able to find and eliminate the race condition, but you could also use a timer that checks every second or two, gets a count of the threads, and if none are still open, it kills the application.
We never did figure out the root programmatic cause, but it was a specific driver version that caused the issue, and upgrading to a new driver fixed the problem.
Unfortunately, this is all the answer I can give, if someone else someday runs into a similar problem...

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