最近用.net开发了个隔时执行的小应用程序,登录MSDTC,放到服务器,运转良好,退出远程桌面,事情出来了,那个可爱的程序不运作了,然后我就搞了个任务计划,做了下,以为完事了,过了一些时间,发现不对劲,还是停止执行程序了,上去一看,又停止了,这时候我不得不重新考虑设置,还是写个系统服务就去吧,写上一段代码先写个服务再说。
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceProcess;
using System.Configuration.Install;
namespace CjjerTest.DotNet.ServiceDST
{
// 应用程序
public class MyFirstService : System.ServiceProcess.ServiceBase
{
public MyFirstService()
{
this.CanPauseAndContinue = true;
this.CanShutdown = true;
this.CanHandleSessionChangeEvent = false;
this.ServiceName = "MyFirstService";
}
protected override void OnStart(string[] args){
}
protected override void OnStop(){
}
protected override void OnContinue(){
}
//启动
public static void Main()
{
ServiceBase[] servicesToRun = new ServiceBase[] {new MyFirstService()};
ServiceBase.Run(servicesToRun);
}
}
//安装
[RunInstaller(true)]
public class ProjectInstaller : System.Configuration.Install.Installer
{
private ServiceProcessInstaller myServiceProcessInstaller;
private ServiceInstaller myServiceInstaller;
public ProjectInstaller()
{
this.myServiceProcessInstaller = new ServiceProcessInstaller();
this.myServiceInstaller = new ServiceInstaller();
// 安装
// 用户名 和 密码
this.myServiceProcessInstaller.Account = ServiceAccount.LocalSystem;
this.myServiceProcessInstaller.Username = null;
this.myServiceProcessInstaller.Password = null;
// 服务名称,这样可以在net stop XX 里面使用了
// 启动类型
this.myServiceInstaller.ServiceName = "MyFirstService";
this.myServiceInstaller.StartType = ServiceStartMode.Automatic;
// 加入
this.Installers.AddRange(new Installer[] {this.myServiceProcessInstaller, this.myServiceInstaller});
}
}
}
其中在启动的代码中我们可以执行:
protected override void OnStart(string[] args){
StreamWriter sw=new StreamWriter(@"E:\web\web\net\test\sernet.txt",true);
sw.Write("\r\n另一条数据");
sw.Close();
base.OnStart( args );
}
或者创建另一条线程执行其他程序。
1、编译
csc cservice.cs
2、安装
installutil cservice.exe
3、启动服务
net start MyFirstService
4、停止服务
net stop MyFirstService
5、卸载
installutil /u cservice.exe
天气:大雨,ccdot发表于2008-4-23 10:44:21,阅读了198次,共有个0回复.