您更改 Main 方法;
static partial class Program
{
static void Main(string[] args)
{
RunAsService();
}
static void RunAsService()
{
ServiceBase[] servicesToRun;
servicesToRun = new ServiceBase[] { new MainService() };
ServiceBase.Run(servicesToRun);
}
}
然后创建新的 Windows 服务(MainService)和安装程序类(MyServiceInstaller);
主服务.cs;
partial class MainService : ServiceBase
{
public MainService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
}
protected override void OnStop()
{
base.OnStop();
}
protected override void OnShutdown()
{
base.OnShutdown();
}
}
我的服务安装程序.cs;
[RunInstaller(true)]
public partial class SocketServiceInstaller : System.Configuration.Install.Installer
{
private ServiceInstaller serviceInstaller;
private ServiceProcessInstaller processInstaller;
public SocketServiceInstaller()
{
InitializeComponent();
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.ServiceName = "My Service Name";
var serviceDescription = "This my service";
Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
}
}