我有一个简单的C#应用程序需要作为服务运行。如何使它作为服务而不仅仅是可执行文件运行?
我有一个简单的C#应用程序需要作为服务运行。如何使它作为服务而不仅仅是可执行文件运行?
Visual C# 2010 Recipes中有一个示例,可以精确地演示如何实现此操作,我已经尝试使用VS 2008和.NET 3.5。
具体步骤如下:
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);
}
}
有一个开源框架可以将.NET应用程序作为Windows服务托管。安装和卸载Windows服务非常方便,它的解耦性也很好。请查看这篇文章:Topshelf Windows Service Framework Post
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();
}