Preventing Exceptions from 3rd party component from crashing the entire application - c#

I am writing a multi-threaded application that relies on some third party DLLs. My problem is that when using an object from the third party library, if it raises an exception while running, I am unable to catch it and it bubbles up and kills the entire application. I have many different threads each using its own object from this third party library and I need the thread that was using that copy of the object to be able to catch and deal with the exception.
Based on what I've read, it seems like most likely the 3rd party library is actually making its own threads and allowing uncaught exceptions. The .NET 2.0+ behavior allows these exceptions to kill the entire application. I'm aware of AppDomain.CurrentDomain.UnhandledException, but that does not allow you to prevent application shutdown.
For reference, I'm writing a console application in .NET 4.0. Does anyone have any solution/advice to stop these exceptions from killing my application?

One thing you might look at is the HandleProcessCorruptedStateExceptionsAttribute attribute.
I don't know if this is your problem or not, but I had to recently use this attribute on a method that was calling a function in a third party COM object. This attribute is new to .net 4.0. My basic understanding is that the 4.0 framework will by default not bubble up an exception thrown in certain situations where it feels the 3rd party exception may have introduced some instabilty. I think this pertains mostly to situations where the 3rd party component is unmanaged. I am not sure, but it resolved my issue.
The usage looks like this:
[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptionsAttribute()]
private void ThirdPartyCall()
{
try
{
return Call3rdPartyFunction()
}
catch (Exception exInstantiate)
{
...
}
}
More information: http://msdn.microsoft.com/en-us/magazine/dd419661.aspx

The issue is probably that exceptions thrown on background threads are not caught once they bubble out of the thread proc.
This seems like a non-obvious duplicate of How to prevent an exception in a background thread from terminating an application?

You can stop application crash by doing this:
AppDomain.CurrentDomain.UnhandledException += (sender, e2) =>
{
Thread.CurrentThread.Join();
};
But uncaught exception from 3d party components mean that components don't do their job properly. If you don't care if they don't do the job better don't use them.

Related

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.

Restricting thread creation

Is it possible to control certain permissions of a thread (and most particularly, threads created from it) in C#?
I am developing a C# app, where a new thread is created and executes certain user given code.
How can i control the operations that the user code CAN and CANNOT perform? is this possible?
In particular, i would like to restrict access to certain APIs from the use code.
One specific example is that i want to disable the ability to spawn off new threads from the user code.
*The reason for this is that the user code may spawn off new threads that may not handle exceptions themselves, leading to the crash of the entire application.
There is no built in way to block creation of the threads in .Net as creation of the tread does not require any additional permissions.
There are also multiple ways of how user's code can spawn another thread.
If your goal is to execute hostile external assemblies you need to protect from more than just thread creation (i.e. StackOverflowException is very easy to throw and bring process down without creating new threads).
One way to insulate your application from the 'plugin' is to use a separate AppDomain to host it. This is not easy, however, mainly because the insulation requires marshaling of references. You can never have a direct reference to an instance in another AppDomain, as this breaks the insulation, so .NET supports a sophisticated proxying model. The downside to this is that all of your code must be written with this proxying in mind, with your proxied reference objects deriving from MarshalByRefObject and all non-proxied objects must support serialization to cross the remoting boundaries by copying. All of this naturally comes with a performance hit, as well. Once you've done this work, though, you can now allow an AppDomain to 'crash' without bringing down your entire application, though your main application will still have to handle the resulting exceptions (any marshaled reference call can throw a RemotingException if the reference has 'died'.)
The next step up in isolation is to create an external hosting process and use some form of inter-process communication to interact with the external code. This gives you excellent isolation (even protection against most unmanaged code unruliness: buggy unmanaged code in an AppDomain can still bring down the whole app) but it adds yet more complexity and performance overhead.
Why don't you try this code.
Application.ThreadException += OnHandledException;
private static void OnHandledException(object sender, ThreadExceptionEventArgs e) {
//handle here
}
If your concern is about unhandled exception. That snippet can do the trick.

AppDomains vs. a robust server

after doing some research it seems that AppDomains are not really a tool for building a hosting server. From my understanding, the hosting server will still crash if there is an unhandled exception in a created AppDomain (if the exception is thrown from a thread in the created AppDomain). So in that case if the hosting server hosts a service which leaks exceptions this will bring down the default AppDomain as well.
So I guess from a server architecture point-of-view there is nothing better than creating child processes and monitoring them.
Is that correct or am I missing something with AppDomains?
thanks,
Christoph
If you can control the threads created in the other AppDomain, you can also handle exceptions by using catch-all blocks in the thread main method.
Other than that, as long as you use the default host, I believe that your assumption is correct. However, if you host the runtime yourself, you can also handle unhandled exceptions.
From a forum post on the topic:
Well, it is possible. You'd have to
create your own CLR host. That starts
with ICorBindToRuntimeEx(). You get
to have full control of AppDomains
that throw exceptions. And it's being
used by MSFT software like ASP.NET and
SQL Server 2005. When you write a
service, you are working with the
default CLR host implementation and it
terminates the process when any
unhandled exception is raised,
regardless of what AppDomain caused
the exception.
Problem is, hosts like ASP.NET and SQL
server have a very well defined code
execution path. In a web server,
managed code runs because of a page
request. In a dbase server, it runs
because of a query. When something
bad happens, they have the luxury of
simply aborting everything that the
request started (killing the
AppDomain) and returning a "sorry,
couldn't do it" status back to the
client. You might have seen it,
crashing the forums server on the old
web site was pretty trivial but didn't
stop it from serving other requests.
Not actually 100% sure about that.
Your service implementation is
probably not nearly as clean. I can't
tell, you didn't say anything about
it. It general, there's a problem
with aborting a thread. You always
have to abort a thread when there's an
unhandled exception. A service
typically has one thread, started by
the OnStart() method. Aborting it
kills the server until somebody stops
and starts it again.
You can definitely make it more
resilient than that, you could start a
"master" thread that launches child
threads in response to external events
that makes your service do its job.
Having a child thread terminated
because of an unhandled exception is
something you could possibly recover
from. But then, if you make that next
step, why not have the child thread
catch an exception and pass it back to
the master thread so it can make an
intelligent decision about what to do
next.
The cold hard fact of the default CLR
host is: if you are not willing to
deal with failure, it is not going to
do the job for you. And it shouldn't,
the .NET 1.x behavior to threads that
died with exceptions was a major
mistake that got corrected in .NET
2.0.
You know what to do: handle failure.
Or write you own host. Or accept that
things could be beyond your control
and log a good error message so you
can tell your customer what to do.
I'd strongly recommend the latter.

Unhandled Exception in Windows Service

I am using system.timer in a windows service application (c#) and have added:
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(MyExceptionHandler);
To handle my exceptions, does this work in a Windows Service as it does not seem to work?
Does anyone have any alternative ideas?
This mechanism will work to capture Unhandled Exceptions in any environment including Windows Services. However there are some limitations on what kind of exceptions can be handled in this way. For instance, a StackOverFlowException may be unhandled but do to it's nature you won't ever see it go through an UnhandledException handler.
Why do you think this is not working? Have you tried attaching to the process with a debugger , enabling first chance exceptions and see what is going on?
Why do you have an unhandled exception in a service? What is the exception? Some exceptions have "special behavior" (and another link here for .NET 4 changes to corrupted state exceptions).
Also, what are you trying to do in the handler? Maybe the actions you're trying to do in the handler are what's limited when running as a service.

Handling uncaught exceptions in C# console application

I'm currently writing a server that hosts several modules. The server runs each module in a separate AppDomain. What I want to achieve is exception isolation, i.e. when one module throws an exception I don't want whole process to terminate, just this specific AppDomain. I know that I can tell CLR to fallback to old behaviour (.NET 1.0) when all uncaught exceptions in different threads were swallowed. However, this is not the most 'elegant' solution.
How about subscribing to this event:
AppDomain.CurrentDomain.UnhandledException
You'll have to cast the ExceptionObject property from type Object to Exception.
Hope that helps.

Categories

Resources