【发布时间】:2013-05-02 21:26:15
【问题描述】:
我正在学习 C#。我阅读了 Andrew Troelsen “C# and the .NET Platform”和 Jeffrey Richter 的“CLR via C#”的书籍。现在,我正在尝试制作应用程序,它将从某个目录加载程序集,将它们推送到 AppDomain 并运行包含的方法(支持插件的应用程序)。这是公共接口所在的DLL。我将它添加到我的应用程序以及所有带有插件的 DLL 中。 MainLib.DLL
namespace MainLib
{
public interface ICommonInterface
{
void ShowDllName();
}
}
这里是插件: PluginWithOutException
namespace PluginWithOutException
{
public class WithOutException : MarshalByRefObject, ICommonInterface
{
public void ShowDllName()
{
MessageBox.Show("PluginWithOutException");
}
public WithOutException()
{
}
}
}
还有一个: PluginWithException
namespace PluginWithException
{
public class WithException : MarshalByRefObject, ICommonInterface
{
public void ShowDllName()
{
MessageBox.Show("WithException");
throw new NotImplementedException();
}
}
}
这是一个应用程序,它加载 DLL 并在另一个 AppDomain 中运行它们
namespace Plug_inApp
{
class Program
{
static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem(CreateDomainAndLoadAssebly, @"E:\Plugins\PluginWithException.dll");
Console.ReadKey();
}
public static void CreateDomainAndLoadAssebly(object name)
{
string assemblyName = (string)name;
Assembly assemblyToLoad = null;
AppDomain domain = AppDomain.CreateDomain(string.Format("{0} Domain", assemblyName));
domain.FirstChanceException += domain_FirstChanceException;
try
{
assemblyToLoad = Assembly.LoadFrom(assemblyName);
}
catch (FileNotFoundException)
{
MessageBox.Show("Can't find assembly!");
throw;
}
var theClassTypes = from t in assemblyToLoad.GetTypes()
where t.IsClass &&
(t.GetInterface("ICommonInterface") != null)
select t;
foreach (Type type in theClassTypes)
{
ICommonInterface instance = (ICommonInterface)domain.CreateInstanceFromAndUnwrap(assemblyName, type.FullName);
instance.ShowDllName();
}
}
static void domain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message);
}
}
}
我希望,如果我在另一个域中运行instance.ShowDllName();(也许我做错了?)未处理的异常将删除它运行的域,但默认域将起作用。但在我的情况下 - 默认域在另一个域中发生异常后崩溃。请告诉我我做错了什么?
【问题讨论】:
-
你错了。 任何应用程序域中未处理的异常将导致整个过程中断。
-
您要么需要处理异常,要么会导致整个过程中断。 stackoverflow.com/questions/7071957/…
-
好的,有什么办法可以捕捉到这个异常,在 MessageBox 中显示“PluginsWithException crashed”之类的东西,应用程序不会崩溃?
-
如您所见,我尝试使用“domain.FirstChanceException += domain_FirstChanceException;”,但没有帮助(
-
如果你不想让它崩溃,你需要处理异常。尝试捕获 NotImplementedException
标签: c# exception .net-assembly appdomain