【问题标题】:Silently update a Windows service静默更新 Windows 服务
【发布时间】:2011-01-04 13:17:06
【问题描述】:

我已经构建了一个 Windows 服务,现在我希望它能够自动更新。我已经阅读了有关创建第二个服务来执行此操作或其他程序的信息,不能使用单击一个,myBuild 呢?有人知道吗?什么是最好的方法?我可以只更改程序集吗?

【问题讨论】:

    标签: c# .net windows-services auto-update


    【解决方案1】:

    如果您希望在执行更新时运行服务,这是我之前为实现此目的所做的:

    1. 将可更新逻辑放入单独的 DLL。
    2. 在您的服务中创建一个 AppDomain。
    3. 创建文件监视器,在您复制该文件时触发事件(您可以使用 MSFT Ent Lib Updates)
    4. 卸载旧 dll,同时阻塞(排队)从该 dll 执行内容的线程
    5. 将新的 dll 文件加载到应用程序域中。
    6. 让您的线程知道继续处理。

    【讨论】:

      【解决方案2】:
      1. 下载新的 exe 和任何其他程序集。
      2. 重命名现有程序集。
      3. 复制到您的新程序集中。
      4. 重新启动服务。您可以将服务重启功能构建到您的主服务 exe 中。
      5. 当服务启动时,检查第 2 步中重命名的文件并删除它们以进行清理。

      要重启你的服务

      System.Diagnostics.Process.Start
          (System.Reflection.Assembly.GetEntryAssembly().Location)
      

      那就为你效劳

          private const string _mutexId = "MyUniqueId";
          private static Mutex _mutex;
          /// <summary>
          /// The main entry point for the application.
          /// </summary>
          static void Main()
          {
              try
              {
                  bool alreadyRunning = false;
                  try
                  {
                      Mutex.OpenExisting(_mutexId);
                      alreadyRunning = true;
                  }
                  catch (WaitHandleCannotBeOpenedException)
                  {
                      alreadyRunning = false;
                  }
                  catch
                  {
                      alreadyRunning = true;                   
                  }
                  if (alreadyRunning)
                  {
                      using (ServiceController sc = new ServiceController("MyServiceName"))
                      {
                          sc.Stop();
                          sc.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 120));
                          sc.Start();
                      }
                      return;
                  }
              }
              catch
              {
              }
              _mutex = new Mutex(true, _mutexId);
      
              ServiceBase[] ServicesToRun;
              ServicesToRun = new ServiceBase[] 
              { 
                  new MyService() 
              };
              // Load the service into memory.
              ServiceBase.Run(ServicesToRun);
              _mutex.Close();
          }
      

      【讨论】:

        【解决方案3】:

        您可以修改您的 Windows 服务,使其只是您的主应用程序的运行程序,并具有更新您的主应用程序的功能。

        所以你会有:

        • Service.exe:运行 Application.exe,监控远程位置以获取 Application.exe 的更新。向 Application.exe 发送启动/停止事件

        • Application.exe:以前是您的 Service.exe。接收开始/停止事件。

        【讨论】:

        • ...对不起,可能解释得不是很好。在凌晨 3 点写 SO 答案可能不是最好的主意;)
        猜你喜欢
        • 2012-06-05
        • 2021-11-05
        • 1970-01-01
        • 1970-01-01
        • 2014-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多