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

l--*_*''' 6 c#

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

Aar*_*web 3

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

相当于:

  1. 在 Visual Studio 中创建新的“Windows 服务”应用程序
  2. 将应用程序的源代码移植到服务的执行模型中,也就是您的 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);
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

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

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

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