c# - 如何使应用程序作为服务运行?

时间:2010-07-12 20:18:40

标签: c#

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

4 个答案:

答案 0 :(得分:3)

visual studio中有一个名为“Windows Service”的模板。如果您有任何问题让我知道,我会整天写服务。

答案 1 :(得分:2)

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

相当于:

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

    [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);
        }
    }
    
  4. 最后,您将使用命令行实用程序来实际安装该服务 - 您可以在此处了解其工作原理:

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

    如果您有任何问题,请与我们联系。

答案 2 :(得分:2)

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

答案 3 :(得分:0)

我想展示一种轻松运行服务的方式

起初,您想知道服务是否停止或其他状态:

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();
    }