c# – 卸载AppDomain后删除dll文件

我正在尝试制作一个游戏引擎,试图复制逐个统一的功能,

为了加载一些脚本,我没有问题,但当我必须重新加载它们时,单声道编译失败,告诉我已经访问DLL,或者无法删除DLL文件.

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Diagnostics;
using System.Security.Policy;
using System.Security;
using System.Security.Permissions;

public class Proxy : MarshalByRefObject
{
    public Assembly GetAssembly(string assemblyPath)
    {
        try
        {
            byte[] response = new System.Net.WebClient().DownloadData(assemblyPath);
            return Assembly.ReflectionOnlyLoad(response);
        }
        catch (Exception)
        {
            return null;
        }
    }

    public Assembly GetAssembly2(string assemblyPath, AppDomain domain)
    {
        try
        {
            byte[] bytesDLL = new System.Net.WebClient().DownloadData(assemblyPath);
            return domain.Load(bytesDLL);
        }
        catch (Exception)
        {
            return null;
            // throw new InvalidOperationException(ex);
        }
    }

    public Assembly GetAssemblyByName(AssemblyName name, AppDomain domain)
    {
        return domain.ReflectionOnlyGetAssemblies().
        SingleOrDefault(assembly => assembly.GetName() == name);
    }
}

class Program
{
    public static AppDomain domain;
    public static Assembly assembly;
    public static Type type;
    public static String dllPath;
    public static String scriptPath;
    public static String className;
    public static String file;
    public static dynamic instance;

    private static bool Compile(String path, out String dir)
    {       
        ProcessStartInfo start = new ProcessStartInfo();
        dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        dir = Path.Combine(dir, Path.GetFileNameWithoutExtension(path) + ".dll");

        if (File.Exists(dir))
        {
            Console.WriteLine("???????");
            File.Delete(dir);
            Console.WriteLine("???????2");
        }

        start.FileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Mono\\lib\\mono\\4.5\\mcs.exe");
        start.UseShellExecute = false;
        start.RedirectStandardError = true;
        start.RedirectStandardOutput = true;
        start.Arguments = "\"" + path + "\" " + "/target:library" + " " + "/out:" + "\"" + dir + "\""; //+ " " + "/reference:OctogonEngine.dll" + " /reference:AssimpNet.dll";

        using (Process process = Process.Start(start))
        {
            using (StreamReader reader = process.StandardError)
            {
                string result = reader.ReadToEnd();
                Console.WriteLine(result);
            }

            using (StreamReader reader = process.StandardOutput)
            {
                string result = reader.ReadToEnd();
                Console.WriteLine(result);
            }
        }

        Console.WriteLine("compilation ok");
        return (true);
    }

    public static void Unload()
    {
        FileStream[] streams = null;

        if (assembly != null)
            streams = assembly.GetFiles();

        instance = null;
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
        type = null;
        assembly = null;
        AppDomain.Unload(domain);
        assembly = null;

        if (streams != null)
        {
            for (int i = 0; i < streams.Length; i++)
            {
                streams[i].Dispose();
            }
        }

        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
        Directory.Delete(cachePath, true);
        return;
    }

    static Assembly GetAssemblyByName(string name, AppDomain domain)
    {
        return domain.GetAssemblies().
               SingleOrDefault(assembly => assembly.GetName().Name == name);
    }

    public static String cachePath = "./cache/";

    public static void Load()
    {
        Directory.CreateDirectory(cachePath);

        if (Compile(scriptPath, out Program.dllPath))
        {
            if (File.Exists(Program.dllPath))
            {
                className = Path.GetFileNameWithoutExtension(Program.dllPath);

                AppDomainSetup setup = new AppDomainSetup();
                setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
                setup.ShadowCopyFiles = "true";
                setup.CachePath = cachePath;
                domain = AppDomain.CreateDomain(className, null, setup);
                domain.DoCallBack(() => AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName("test.dll")));
                var assemblyLoader = (Proxy)domain.CreateInstanceAndUnwrap(typeof(Proxy).Assembly.FullName, typeof(Proxy).FullName);
                assembly = assemblyLoader.GetAssembly(Program.dllPath);

                /*if (assembly == null)
                {
                    Console.WriteLine("damn");
                }*/

                if (assembly != null)
                {
                    type = assembly.GetType(className);
                }

                if (File.Exists(scriptPath))
                    Program.file = File.ReadAllText(scriptPath);
            }
        }
    }

    static bool check = false;

    static void AppDomainInit(string[] args)
    {
        if (!File.Exists(args[0]))
        {
            return;
        }
    }

    public static void init(String scriptPath)
    {
        if (File.Exists(scriptPath))
        {
            Program.file = File.ReadAllText(scriptPath);
            Program.scriptPath = scriptPath;
            Program.Load();
        }
    }

    static void Main(string[] args)
    {
        Program.init(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "test.cs"));
        Program.Unload();
        //here is the crash :/
        File.Delete(Program.dllPath);
        Console.WriteLine("???");
    }
}

(要进行测试,您可能需要在执行目录中复制mono,可以在:http://www.mono-project.com/download/找到)

有没有人知道我可以做什么,强制删除该DLL文件,或使该文件可访问删除?

如果没有,是否有人对统一加载和重新加载脚本的方式有所了解,如何使其成为好方法?

最佳答案 我的解决方案,如果有人需要它,是用CSharpCodeProvider编译的,

这个参数:

CompilerParameters compilerParams = new CompilerParameters
{
GenerateInMemory = true,
GenerateExecutable = false,
IncludeDebugInformation = true
};

然后我甚至不需要从它构建一个DLL,结果是一个可用的程序集.

如果你真的需要在运行时加载然后删除一个程序集,你仍然可以使用它

byte[] bytes = File.ReadAllBytes("pathtoyourdll");
AppDomain.CurrentDomain.Load(bytes);

然后你可以删除dll,但需要一些内存.

点赞