我有一个别人写的dll,有很多缺陷。假设此DLL中只定义了一个类。我需要导入此DLL并创建此类的实例。 DLL代码可能如下:
[Serializable()]
public class makeExceptionClass
{
public bool isStringNormalized(string aString)
{
// A null check should be performed
return aString.IsNormalized();
}
}
我编写了一个小程序来检查即使dll崩溃我的程序是否仍然可以运行。该计划只是一个概念证明。它需要两个参数,第一个用于直接从程序集加载DLL,第二个用于引发崩溃。 该计划的代码如下:
class Program
{
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
static void Main(string[] args)
{
string typeOfLoading = args[0];
string crash = args[1];
// Load the DLL
if (typeOfLoading.Equals("direct") == true)
{
Console.WriteLine("Loading directly a DLL");
Assembly anAssembly = Assembly.Load("unloadableDLL"); // Directly load the DLL
unloadableDLL.makeExceptionClass anObject = (unloadableDLL.makeExceptionClass)anAssembly.CreateInstance("unloadableDLL.makeExceptionClass");
if (crash.Equals("crash") == true)
{
bool test = anObject.isStringNormalized(null);
}
else
{
bool test = anObject.isStringNormalized("test");
}
}
else if (typeOfLoading.Equals("indirect") == true)
{
Console.WriteLine("Loading indirectly a DLL");
AppDomain anAppDomain = AppDomain.CreateDomain("RemoteLoaderDomain"); // Assume it does not fail;
Type t = typeof(unloadableDLL.makeExceptionClass);
unloadableDLL.makeExceptionClass anObject = (unloadableDLL.makeExceptionClass)anAppDomain.CreateInstanceAndUnwrap("unloadableDLL", t.FullName);
if (crash.Equals("crash") == true)
{
bool test = anObject.isStringNormalized(null);
}
else
{
bool test = anObject.isStringNormalized("test");
}
Console.WriteLine("Unloading the domain");
AppDomain.Unload(anAppDomain);
}
else
{
// don't care
}
// terminate
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
问题是无论dll是直接加载还是加载到AppDomain,我的程序都会崩溃。 我是C#的新手(我今天早上开始),但我有C ++背景。
答案 0 :(得分:1)
在您的通话中添加try / catch:
try
{
if (crash.Equals("crash") == true)
{
bool test = anObject.isStringNormalized(null);
}
else
{
bool test = anObject.isStringNormalized("test");
}
} catch (Exception ex) {
Console.WriteLine("exception in dll call: "+ex);
}