C# - 如何将应用程序作为服务运行?

9

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


可能是重复的问题:使用C#创建Windows服务的资源 - Joe
这里我找到了逐步说明:https://dev59.com/cHRB5IYBdhLWcg3wiHv7#593803 - Rekshino
4个回答

3

Visual C# 2010 Recipes中有一个示例,可以精确地演示如何实现此操作,我已经尝试使用VS 2008和.NET 3.5。

具体步骤如下:

  1. Create a new "Windows Service" application in Visual Studio
  2. Port your application's source into the service's execution model, AKA your Main function becomes part of an event handler triggered by a timer object or something along those lines
  3. Add a Service Installer class to your Windows Service project - it'll look something like this code snippet below:

    [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 如果您有任何疑问,请告诉我。

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

非常感谢,乔纳森。我一定会接受你的帮助。 - Alex Gordon

2

有一个开源框架可以将.NET应用程序作为Windows服务托管。安装和卸载Windows服务非常方便,它的解耦性也很好。请查看这篇文章:Topshelf Windows Service Framework Post


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接