c#之添加window服务(定时任务)
时间: 2023-11-13 17:03:23 浏览: 32
要在 C# 中添加 Windows 服务,你需要使用 System.ServiceProcess 命名空间中的 ServiceBase 类。下面是一个简单的示例,演示如何创建一个 Windows 服务,并将其安装到计算机上:
首先,创建一个新的 C# 项目并添加一个新的类文件。在类文件中,定义一个类,继承自 ServiceBase 类,并重写 OnStart 和 OnStop 方法:
```csharp
using System.ServiceProcess;
namespace MyService
{
public partial class MyService : ServiceBase
{
public MyService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
// 在此处启动服务
}
protected override void OnStop()
{
// 在此处停止服务
}
}
}
```
在 OnStart 方法中,写下你想要在服务启动时执行的代码。在 OnStop 方法中,写下你想要在服务停止时执行的代码。
然后,打开项目属性,选择“应用程序”选项卡,并将输出类型设置为“Windows 应用程序”。这将使项目生成为可安装的 Windows 服务。
接下来,你需要编写一些代码来安装和卸载服务。可以使用 System.Configuration.Install 命名空间中的 InstallUtil 工具来执行这些操作。在项目中添加一个新的安装程序类,如下所示:
```csharp
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
[RunInstaller(true)]
public class MyServiceInstaller : Installer
{
private ServiceInstaller serviceInstaller;
private ServiceProcessInstaller processInstaller;
public MyServiceInstaller()
{
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();
// 设置服务的名称和显示名称
serviceInstaller.ServiceName = "MyService";
serviceInstaller.DisplayName = "My Service";
// 设置服务的启动类型为自动
serviceInstaller.StartType = ServiceStartMode.Automatic;
// 将服务安装程序和进程安装程序添加到安装程序集合中
Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
}
}
```
在这个类中,你需要设置服务的名称、显示名称和启动类型。在 Installers 集合中添加 ServiceInstaller 和 ServiceProcessInstaller 对象,以便安装程序可以正确地安装和卸载服务。
最后,在 Visual Studio 中打开“命令提示符”窗口,并导航到项目的输出目录。运行以下命令安装服务:
```bat
installutil MyService.exe
```
运行以下命令卸载服务:
```bat
installutil /u MyService.exe
```
这些命令将使用 InstallUtil 工具来安装和卸载服务。注意,需要使用管理员权限运行命令提示符窗口,才能正确执行这些命令。
希望这个简单的示例可以帮助你开始编写自己的 Windows 服务。