3

次のサンプル アプリでは、新しい を作成しAppDomain、シャドウ コピーを有効にして実行します。新しいものからAppDomain、元のメイン exe を削除 (置換) しようとします。しかし、「アクセスが拒否されました」というエラーが表示されます。興味深いことに、プログラムを起動した後、Windows エクスプローラーからメインの exe の名前を変更できます (削除はできません)。

シャドウ コピーは、メイン exe の実行時上書きに対して機能しますか?

static void Main(string[] args)
{
    // enable comments if you wanna try to overwrite the original exe (with a 
    // copy of itself made in the default AppDomain) instead of deleting it

    if (AppDomain.CurrentDomain.IsDefaultAppDomain())
    {
        Console.WriteLine("I'm the default domain");
        System.Reflection.Assembly currentAssembly = System.Reflection.Assembly.GetExecutingAssembly();
        string startupPath = currentAssembly.Location;

        //if (!File.Exists(startupPath + ".copy"))
        //    File.Copy(startupPath, startupPath + ".copy");

        AppDomainSetup setup = new AppDomainSetup();
        setup.ApplicationName = Path.GetFileName(startupPath);
        setup.ShadowCopyFiles = "true";

        AppDomain domain = AppDomain.CreateDomain(setup.ApplicationName, AppDomain.CurrentDomain.Evidence, setup);
        domain.SetData("APPPATH", startupPath);

        domain.ExecuteAssembly(setup.ApplicationName, args);

        return;
    }

    Console.WriteLine("I'm the created domain");
    Console.WriteLine("Replacing main exe. Press any key to continue");
    Console.ReadLine();

    string mainExePath = (string)AppDomain.CurrentDomain.GetData("APPPATH");
    //string copyPath = mainExePath + ".copy";
    try
    {
        File.Delete(mainExePath );
        //File.Copy(copyPath, mainExePath );
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error! " + ex.Message);
        Console.ReadLine();
        return;
    }

    Console.WriteLine("Succesfull!");
    Console.ReadLine();
}
4

3 に答える 3

0

これは MEF の興味深い使用例であるため、C# で実行中のコードをホットスワップする方法の簡単なデモを作成しました。これは非常に単純で、多くのエッジ ケースを除外します。

https://github.com/ieb/MefExperiments

注目すべきクラス:

  • src/PluginWatcher/PluginWatcher.cs-- コントラクトの新しい実装のフォルダーを監視します
  • src/HotSwap.Contracts/IHotSwap.cs-- ホットスワップの最小基本契約
  • src/HotSwapDemo.App/Program.cs-- ライブ コード スワップはありますか

これにより、Plugins フォルダー内のタスクがロックされない.dllため、新しいバージョンがデプロイされたら古いバージョンを削除できます。それが役立つことを願っています。

于 2014-03-17T11:24:17.330 に答える