【问题标题】:c# - how do i make application run as a service?c# - 我如何让应用程序作为服务运行?
【发布时间】:2010-07-12 20:18:39
【问题描述】:

我有一个需要作为服务运行的简单 c# 应用程序。如何让它作为服务而不是可执行文件运行?

【问题讨论】:

标签: c#


【解决方案1】:

Visual C# 2010 Recipies 中有一个示例,它将向您确切展示如何执行此操作,我已尝试使用 VS 2008 和 .NET 3.5。

就是这样:

  1. 在 Visual Studio 中创建一个新的“Windows 服务”应用程序
  2. 将应用程序的源代码移植到服务的执行模型中,也就是您的 Main 函数成为由计时器对象或类似内容触发的事件处理程序的一部分
  3. 将 Service Installer 类添加到您的 Windows 服务项目中 - 它看起来类似于下面的代码 sn-p:

    [RunInstaller(true)]
    public partial class PollingServiceInstaller : Installer
    {
        public PollingServiceInstaller()
        {
            //Instantiate and configure a ServiceProcessInstaller
            ServiceProcessInstaller PollingService = new ServiceProcessInstaller();
            PollingService.Account = ServiceAccount.LocalSystem;
    
            //Instantiate and configure a ServiceInstaller
            ServiceInstaller PollingInstaller = new ServiceInstaller();
            PollingInstaller.DisplayName = "SMMD Polling Service Beta";
            PollingInstaller.ServiceName = "SMMD Polling Service Beta";
            PollingInstaller.StartType = ServiceStartMode.Automatic;
    
            //Add both the service process installer and the service installer to the
            //Installers collection, which is inherited from the Installer base class.
            Installers.Add(PollingInstaller);
            Installers.Add(PollingService);
        }
    }
    

最后,您将使用命令行实用程序来实际安装该服务 - 您可以在此处了解其工作原理:

http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/d8f300e3-6c09-424f-829e-c5fda34c1bc7

如果您有任何问题,请告诉我。

【讨论】:

    【解决方案2】:

    Visual Studio 中有一个名为“Windows Service”的模板。如果您有任何问题,请告诉我,我整天都在写服务。

    【讨论】:

    • 非常感谢乔纳森,我一定会接受你的
    【解决方案3】:

    有将 .net 应用程序作为 Windows 服务托管的开源框架。安装、卸载windows服务没有痛苦。它解耦得很好。请查看此帖Topshelf Windows Service Framework Post

    【讨论】:

      【解决方案4】:

      我想展示简单的方式来运行服务

      如果你的服务没有停止或其他状态,首先你想要:

      public static bool isServiceRunning(string serviceName)
          {
              ServiceController sc = new ServiceController(serviceName);
              if (sc.Status == ServiceControllerStatus.Running)
                  return true;
              return false;
          }
      

      接下来如果服务没有运行,你可以使用这个简单的方法

      public static void runService(string serviceName)
          {
              ServiceController sc = new ServiceController(serviceName);
              sc.Start();
          }
      

      【讨论】:

        猜你喜欢
        • 2011-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-13
        • 1970-01-01
        • 2019-04-12
        • 2010-09-08
        相关资源
        最近更新 更多