0

我将动态 dll 添加到我的应用程序中。调用方法后我有内存泄漏。这是我的代码:

static IntfClass GetIClass(string filename)
{
    Assembly classLibrary1 = null;
    using (FileStream fs = File.Open(filename, FileMode.Open))
    {
        using (MemoryStream ms = new MemoryStream())
        {
            byte[] buffer = new byte[1024];
            int read = 0;
            while ((read = fs.Read(buffer, 0, 1024)) > 0)
                ms.Write(buffer, 0, read);
            classLibrary1 = Assembly.Load(ms.ToArray());
        }
    }
    foreach (Type type in classLibrary1.GetExportedTypes())
    {
        if (type.GetInterface("IntfClass") != null)
        return Activator.CreateInstance(type) as IntfClass;
    }
    throw new Exception("no class found that implements interface IntfClass");
}

调用:

IntfClass class1 = GetIClass("myDllName.dll");
Thread t = new Thread(new ParameterizedThreadStart(class1.runReport));
t.Start((object)report);

我添加了线程,如果我的应用程序将控制权转移给 dll,在完成 dll 方法后将控制权交还给我。

4

1 回答 1

0

创建一个单独的 AppDomain 来加载程序集,并尝试使用 AppDomain 的 Unload 方法卸载它。

例如:

void LoadAssembly(){
AppDomain newDomain = AppDomain.CreateDomain("CreateNewDomain");
    newDomain.ExecuteAssembly("filename");
    AppDomain.Unload(newDomain);
}
于 2014-05-09T17:24:53.587 回答