【发布时间】:2010-07-12 20:18:39
【问题描述】:
我有一个需要作为服务运行的简单 c# 应用程序。如何让它作为服务而不是可执行文件运行?
【问题讨论】:
-
在这里我找到了分步说明:stackoverflow.com/a/593803/7713750
标签: c#
我有一个需要作为服务运行的简单 c# 应用程序。如何让它作为服务而不是可执行文件运行?
【问题讨论】:
标签: c#
Visual C# 2010 Recipies 中有一个示例,它将向您确切展示如何执行此操作,我已尝试使用 VS 2008 和 .NET 3.5。
就是这样:
将 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);
}
}
最后,您将使用命令行实用程序来实际安装该服务 - 您可以在此处了解其工作原理:
如果您有任何问题,请告诉我。
【讨论】:
Visual Studio 中有一个名为“Windows Service”的模板。如果您有任何问题,请告诉我,我整天都在写服务。
【讨论】:
有将 .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();
}
【讨论】: