C#创建Windows服务的方式总结
1. 利用.net框架类ServiceBase
==通过继承.net框架类ServiceBase实现,简单兼容性好==
* 步骤一:新建一个Windows服务
namespace WindowsService_test
{
public partial class Service1 : ServiceBase
{
readonly Timer _timer;
private static readonly string FileName = Path.GetDirectoryName ( Assembly.GetExecutingAssembly ( ).Location ) + @"\" + "test.txt";
public Service1 ( )
{
InitializeComponent ( );
_timer = new Timer ( 5000 )
{
AutoReset = true ,
Enabled = true
};
_timer.Elapsed += delegate ( object sender , ElapsedEventArgs e )
{
this.witre ( string.Format ( "Run DateTime {0}" , DateTime.Now ) );
};
}
protected override void OnStart ( string [ ] args )
{
this.witre(string.Format("Service1 Start DateTime {0}", DateTime.Now));
}
protected override void OnStop ( )
{
this.witre(string.Format("Service1 Stop DateTime {0}", DateTime.Now) + Environment.NewLine);
}
void witre ( string context )
{
StreamWriter sw = File.AppendText ( FileName );
sw.WriteLine ( context );
sw.Flush ( );
sw.Close ( );
}
}
}
- 步骤二:添加Installer
namespace WindowsService_test
{
[RunInstaller(true)]
public partial class Installer1 : System.Configuration.Install.Installer
{
private ServiceInstaller serviceInstaller;
private ServiceProcessInstaller processInstaller;
public Installer1 ()
{
InitializeComponent();
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.ServiceName = "my_WindowsService";
serviceInstaller.Description = "WindowsService_Description";
serviceInstaller.DisplayName = "WindowsService_DisplayName";
Installers.Add ( serviceInstaller );
Installers.Add ( processInstaller );
}
}
}
- 步骤三:安装,卸载
- 以管理员身份运行Cmd,找到InstallUtil.exe工具,本机为(C:\Windows\Microsoft.NET\Framework\v4.0.30319)
- 运行Cmd命令:InstallUtil WindowsService_test.exe 安装Windows服务
- 运行Cmd命令:InstallUtil /u WindowsService_test.exe 卸载Windows服务
2. 利用组件Topshelf
==Topshelf是一个开源的跨平台的服务框架,支持Windows和Mono,只需要几行代码就可以构建一个很方便使用的服务;代码简单,开源组件,Windows服务可运行多个实例==
* 步骤一:引用程序集TopShelf.dll和log4net.dll
* 步骤二:创建服务类
namespace ConsoleApp_Topshelf
{
public class MyClass
{
readonly Timer _timer;
private static readonly string FileName = Directory.GetCurrentDirectory ( ) + @"\" + "test.txt";
public MyClass ( )
{
_timer = new Timer ( 5000 )
{
AutoReset = true ,
Enabled = true
};
_timer.Elapsed += delegate ( object sender , ElapsedEventArgs e )
{
this.witre ( string.Format ( "Run DateTime {0}" , DateTime.Now ) );
};
}
void witre ( string context )
{
StreamWriter sw = File.AppendText ( FileName );
sw.WriteLine ( context );
sw.Flush ( );
sw.Close ( );
}
public void Start ( )
{
this.witre ( string.Format ( "Start DateTime {0}" , DateTime.Now ) );
}
public void Stop ( )
{
this.witre ( string.Format ( "Stop DateTime {0}" , DateTime.Now ) + Environment.NewLine );
}
}
}
- 步骤三:使用Topshelf宿主我们的服务
namespace ConsoleApp_Topshelf
{
class Program
{
static void Main ( string [ ] args )
{
HostFactory.Run(x =>
{
x.Service<MyClass>((s) =>
{
s.SetServiceName("chao");
s.ConstructUsing(name => new MyClass());
s.WhenStarted((t) => t.Start());
s.WhenStopped((t) => t.Stop());
});
//表示以本地系统账号运行,可选的还有网络服务和本地服务账号
x.RunAsLocalSystem();
//服务的描述
x.SetDescription("Topshelf_Description");
//服务的显示名称
x.SetDisplayName("Topshelf_DisplayName");
//服务名称
x.SetServiceName("Topshelf_ServiceName");
});
}
}
}
- 步骤四:安装,卸载(其中exe就是程序生成的可执行文件)
- ConsoleApp_Topshelf.exe install (安装Windows服务)
- ConsoleApp_Topshelf.exe uninstall (卸载Windows服务)
- TopshelfExample.exe start(启动Windows服务)
- TopshelfExample.exe stop(停止Windows服务)
TopShell简要说明
==引用:http://www.myexception.cn/asp-dotnet/2037966.html==
* topshelf虽小但支持的可配置选项比较多,以下是部分示例:
* SetStartTimeout启动超时
* SetStopTimeout停止超时
* BeforeUninstall卸载前
* AfterUninstall 卸载后回调
* AfterInstall安装后回调
* AfterRollback回滚后回调
* DependsOnMsmq Msmq启动后再启动
* EnablePauseAndContinue支持暂停
* 多实例支持
* 原生服务上是不支持的,topshelf支持使用不同的名称来部署多个同样的程序实例:
* 启动一个新实例:TopshelfExample.exe –instance “newinstallname” install
* 卸载一个实例:TopshelfExample.exe –instance “TopshelfExample2” uninstall
* ==多实例有一个好处就是容灾,当一个服务部署多份时,这样其中任何一个服务实例挂了,剩余的可以继续执行。 多实例可以是主备的方式,主挂了备服务才会执行。也可以以负载均衡的方式实现,多实例抢占进程锁或分布式锁,谁拿到谁执行。==