簡體   English   中英

應用程序使用的 DLL 的熱卸載/重新加載

[英]Hot Unload/Reload of a DLL used by an Application

我有一個應用程序加載一個 DLL 來執行處理的特定部分

Example : "Application.dll" loading "Process.dll" 

Process.dll 在運行時動態加載,使用反射,而不是在應用程序中引用。

處理完成后,DLL 需要在服務器上重新編譯,稍后再次加載回來。
為此,我需要釋放它,否則我會收到以下消息:“無法將文件“Process.dll”復制到“Process.dll”。進程無法訪問文件“Process.dll”,因為它是被另一個進程使用。”

所以問題是:如何在重新加載之前以編程方式從我的應用程序中釋放/釋放/卸載Process.dll 當然,重點是在停止應用程序的情況下執行此操作。

編輯 1:

一個提議的解決方案是這樣的:

AppDomain newDomain4Process = AppDomain.CreateDomain("newDomain4Process");
Assembly processLibrary = newDomain4Process.Load("Process.dll");
AppDomain.Unload(newDomain4Process);

我仍然遇到的問題是,雖然我提供了正確的完整路徑,但我收到了FileNotFound Exception 這篇文章的答案也沒有達到預期的效果。

編輯 2:

這篇文章救了我的命,這是代碼:

class ProxyDomain : MarshalByRefObject
    {
        public Assembly GetAssembly(string AssemblyPath)
        {
            try
            {
                return Assembly.LoadFrom(AssemblyPath);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

   ProxyDomain pd = new ProxyDomain();
   Assembly a = pd.GetAssembly(FullDLLPath);

編輯 3:
不過,我無法訪問 AppDomain 並使用以前的解決方案將其卸載。 當我使用 AppDomain Creation 的經典方法時,我感受到了 Alexei 的警告: AppDomain.Unload “似乎”工作,但程序集仍然加載(模塊視圖)。 所以我在某種程度上仍然有我的問題,因為我不能真正有效地卸載 DLL。

自從我看這個已經有一段時間了,但我很確定您需要創建一個新的AppDomain ,然后在其中加載 DLL。

原因是您不能自行卸載Assembly ,但可以卸載包含AssemblyAppDomain

一旦程序集加載到AppDomain ,就無法卸載。 您必須處理AppDomain 如果您需要在應用程序中加載和卸載程序集,則需要生成一個新的AppDomain並加載該程序集,然后在完成該程序集后銷毀該AppDomain

雖然您似乎根據您的編輯解決了問題,但這里有幾條評論:

注意 Process.dll 中的對象“泄漏”到主 AppDomain 中。 即拋出 Process.dll 中定義並在主 AppDomain 中捕獲的自定義異常將強制 Process.dll 加載到主 AppDomain 中。 執行您感興趣的操作后,檢查主 AppDomain 中加載的程序集列表。

卸載 AppDomain 可能會失敗,並且可能需要很長時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM