65.9K
CodeProject 正在变化。 阅读更多。
Home

应用程序的影子复制

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.88/5 (40投票s)

2008年10月7日

CPOL
viewsIcon

115952

downloadIcon

1345

影子复制的应用程序不会被加载器锁定,因此可以在运行时更新/替换它们。

引言

运行影子复制的应用程序对于自动更新等目的非常有用。在正常执行时,程序集会被加载器锁定,并且在执行期间无法被替换。在影子复制时,所有引用的程序集都会被复制到缓存路径,并从该位置加载/执行 - 因此程序集不会被锁定,并且可以被更改。

背景

这项技术在 ASP.NET 中广为人知,但在应用程序方面,信息很少(甚至在 MSDN 上也很少)。因此,我想分享我的发现。

Using the Code

要从缓存路径执行程序集,我们必须使用加载器/引导程序。这个小程序会创建一个域,应用程序将从中加载。这意味着,当我们想要启动应用程序时,我们必须启动加载器来为我们加载应用程序。

应用程序的代码和所有引用的程序集不需要任何更改。

加载器的代码是

using System;
using System.IO;

namespace Loader
{
    static class Program
    {
        [LoaderOptimization(LoaderOptimization.MultiDomainHost)]
        [STAThread]
        static void Main()
        {
            /* Enable shadow copying */

            // Get the startup path. Both assemblies (Loader and
            // MyApplication) reside in the same directory:
            string startupPath = Path.GetDirectoryName(
				System.Reflection.Assembly
				.GetExecutingAssembly().Location);

            // cache path = directory where the assemblies get
            // (shadow) copied:
            string cachePath = Path.Combine(
                startupPath,
                "__cache");
            string configFile = Path.Combine(
                startupPath,
                "MyApplication.exe.config");
            string assembly = Path.Combine(
                startupPath,
                "MyApplication.exe");

            // Create the setup for the new domain:
            AppDomainSetup setup = new AppDomainSetup();
            setup.ApplicationName = "MyApplication";
            setup.ShadowCopyFiles = "true"; // note: it isn't a bool
            setup.CachePath = cachePath;
            setup.ConfigurationFile = configFile;

            // Create the application domain. The evidence of this
            // running assembly is used for the new domain:
            AppDomain domain = AppDomain.CreateDomain(
                "MyApplication",
                AppDomain.CurrentDomain.Evidence,
                setup);

            // Start MyApplication by executing the assembly:
            domain.ExecuteAssembly(assembly);

            // After the MyApplication has finished clean up:
            AppDomain.Unload(domain);
            Directory.Delete(cachePath, true);
        }
    }
}

关注点

这个简单的程序使我们能够轻松创建自动更新(替换应用程序的程序集)。

历史

  • 2008 年 10 月 7 日 - 初始发布
  • 2008 年 10 月 14 日 - 文章已更新
© . All rights reserved.