AppDomains and Exceptions

M

Michael Bray

I'm writing a library to provide plugin capability to my applications. It
does this by loading DLL's into a new AppDomain for each plugin that is
loaded. Now obviously when I write a plugin, I can make sure that my
plugins don't throw any exceptions. But I certainly can't guarantee that
other people writing plugins won't throw an exception. The problem is that
if one of these other plugins throws an exception, it brings down the
entire application.

Is there anything I can do to prevent Exceptions in other AppDomains from
bringing down the entire app, when I don't own the code that is running in
that AppDomain? I thought I would be able to use
AppDomain.UnhandledException, but as is pointed out in the link below, this
is only a "notification" not a "handler".

UnhandledException is not a handler: (watch the wrap)
http://lab.msdn.microsoft.com/ProductFeedback/viewFeedback.aspx?
feedbackId=FDBK21092

-mdb
 
D

Daniel O'Connell [C# MVP]

Michael Bray said:
I'm writing a library to provide plugin capability to my applications. It
does this by loading DLL's into a new AppDomain for each plugin that is
loaded. Now obviously when I write a plugin, I can make sure that my
plugins don't throw any exceptions. But I certainly can't guarantee that
other people writing plugins won't throw an exception. The problem is
that
if one of these other plugins throws an exception, it brings down the
entire application.

Is there anything I can do to prevent Exceptions in other AppDomains from
bringing down the entire app, when I don't own the code that is running in
that AppDomain? I thought I would be able to use
AppDomain.UnhandledException, but as is pointed out in the link below,
this
is only a "notification" not a "handler".

You might be able to get around it by using a bit of code in the appdomain
that can catch and gracefully handle exceptions, just place a little code
between the plugin client and the client itself that handles that.
 
M

Michael Bray

You might be able to get around it by using a bit of code in the
appdomain that can catch and gracefully handle exceptions, just place
a little code between the plugin client and the client itself that
handles that.

Hi Daniel,

I figured someone might answer with this, but I was hoping that there
would be a more straightforward answer...

The problem is that I (the hosting application) never call the plugin
code. I pass it a pointer to services that the hosting application
provides, like this:

interface IPluginHost
{
void SetHostTitle(string text);
}

interface IPlugin
{
Initialize(IPluginHost host);
}

public class MyPlugin : IPlugin
{
public void Initialize(IPluginHost host)
{
ThreadPool.QueueUserWorkItem(
new WaitCallback(this.DoPluginWork)
);
}

public void DoPluginWork(object state)
{
Thread.Sleep(10000);
host.SetTitle("blah");

// This kills the entire application
throw new Exception();
}
}

public class Form1 : Form, IPluginHost
{
// normal windows form stuff
public void SetHostTitle(string text)
{
// In my host app, this is Invoked to the UI thread
this.Text = text;
}

public Form1()
{
InitializeComponent();
IPlugin myPlugin = new MyPlugin(this);
}
}

Obviously things are more complicated than I show here, but you get the
idea.... Now if I was calling IPlugin functions from my host, then I
could wrap them in a try/catch, but as you can see, that's not the way I
want to do it. I want the plugins to be in charge of their own destiny,
and not have to wait on a 'polling' mechanism from the host to affect
changes in the host.

As you can see, I have no way of putting a try/catch around the work
that the client does from the code in Form1. Of course I could put it
around the code INSIDE DoPluginWork, but that's something I can't
control if other programmers are writing an IPlugin for my application.

Thus I'm looking for some way to prevent THEIR bad programming from
destroying my entire application. I thought that AppDomains would do
this, but that's not what my experience is so far - an exception thrown
in another AppDomain still kills the entire application.

-mdb
 
M

Michael Bray

Hello, Michael!

You can establish a proxy object that will load plugins on the app
domain, and will start it own thread method there, where you can
place try/catch block. This will give you the possibility to catch
all exceptions from plugin worker...

Yes. That's exactly what I do. But Exceptions thrown in the proxy cause
my application to fail. That's what I'm trying to prevent.

-mdb
 
M

Michael Bray

Hello, Michael!

You can establish a proxy object that will load plugins on the app
domain, and will start it own thread method there, where you can
place try/catch block. This will give you the possibility to catch
all exceptions from plugin worker...

Sorry I didn't quite understand what you said, so my previous response was
a bit off... Your solution still suffers from the problem that I have to
rely on the programmer of the plugin to use my Delegate and the
PluginWorkProc function. There's nothing that forces them to do this.

What I'm looking for is a generic way to HANDLE (not just receive
notification of) Exceptions that are thrown in an AppDomain so that the
entire application doesn't die.

It's looking more and more like this can't be done. Disappointing.

-mdb
 
M

Michael Bray

From MSDN:
"The UnhandledExceptionEventHandler delegate for this event provides
default handling for uncaught exceptions. When this event is not
handled, the system default handler reports the exception to the user
and terminates the application. This event occurs only for the
application domain that is created by the system when an application
is started. If an application creates additional application domains,
specifying a delegate for this event in those applications domains has
no effect."

Didn't test it myself, but if you will subscribe to the
UnhandledExceptionEventHandler of main application domain?
Theoretically this should prevent main app domain from exiting....

Yes. In fact, I've even go one step further (or two) by setting the
'SetUnhandledExceptionMode'. These linese are in my Main(...) before
anything else occurs.

Application.ThreadException += new
System.Threading.ThreadExceptionEventHandler
(Application_ThreadException);

Application.SetUnhandledExceptionMode
(UnhandledExceptionMode.CatchException, true);

AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);


-mdb
 
V

Vadik Vaksin

Hello Michael,
Are you absolutely sure you need to open a new AppDomain? Could you load
those plagins just in designated threads? I think this will solve the problem
of killing the application (although I don't know how many other problems
this could bring... ;)

Vadik
 
M

Michael Bray

Are you absolutely sure you need to open a new AppDomain? Could you
load those plagins just in designated threads? I think this will solve
the problem of killing the application (although I don't know how many
other problems this could bring... ;)

My overall design calls for the ability to dynamially load AND unload
plugins, for which I need AppDomains.

Actually I can boil my requirements down to three things:

1. Ability to dynamically load/unload plugins

2. Plugins make function calls to the host application (not the other way
around)

3. Exceptions thrown in the plugin don't kill the app. Preferably, I
should be able to know about the exception so I can shut down that plugin.

There are plenty of examples out there that show how to dynamically load
plugins, but very few do it in AppDomains, so they can't unload them (in
the sense of the DLL being removed from memory).

Here's another option I would consider: If there is a Code Access Security
setting that I could use to specify that the plugin cannot create new
threads, then I would create a new thread for it and run a plugin function
in a try/catch. Anyone know if such a CAS setting exists?

-mdb
 
G

Guest

Michael,

I'm not sure this will work in your application but this is how its work for
csUnit (http://www.csunit.org) :

here is how the test is executed:
public void RunTests(ITestSpec testSpec) {
try {
...
LoadAssembly();
...
RunTests(testSpec);
}
catch(AppDomainUnloadedException) {
...
}
}
Of course, the RunTest function could crash. This function could also open
another threads (at least we are doing this)

Here is the LoadAssembly function:
LoadAssembly() {
FileInfo fi = new FileInfo(_assemblyPathName);
...
String applicationDomainName = AppDomain.CurrentDomain.FriendlyName
+ ":TestExecutor-" + ++_loaderCount;
AppDomainSetup setup = new AppDomainSetup();

setup.ApplicationBase = fi.DirectoryName;
setup.PrivateBinPath = AppDomain.CurrentDomain.BaseDirectory;
setup.ApplicationName = fi.Name;
setup.ShadowCopyFiles = "true";
setup.ShadowCopyDirectories = fi.DirectoryName;

setup.ConfigurationFile = fi.Name + ".config";

_appDomain = AppDomain.CreateDomain(applicationDomainName, null,
setup);
...
try {
_remoteLoader = (RemoteLoader)
_appDomain.CreateInstanceFromAndUnwrap(
//csUnitCorePathFileName, remoteLoaderFullTypeName);
csUnitDll, remoteLoaderFullTypeName);
}
catch(Exception e) {
...
return null;
}

...
_assemblyFullName =
_remoteLoader.LoadAssembly(this._assemblyPathName, assemblyName, this);

...
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top