本文转载:
http://www.cnblogs.com/aierong/archive/2012/05/28/2521409.html
http://www.cnblogs.com/jys509/p/4628926.html
官网github
https://github.com/Topshelf/Topshelf/downloads
b.利用组件Topshelf
本方式特点:代码简单,开源组件,Windows服务可运行多个实例
Topshelf是一个开源的跨平台的服务框架,支持Windows和Mono,只需要几行代码就可以构建一个很方便使用的服务. 官方网站:http://topshelf-project.com
第1步:引用程序集TopShelf.dll和log4net.dll
第2步:创建一个服务类MyClass,里面包含两个方法Start和Stop,还包含一个定时器Timer,每隔5秒往文本文件中写入字符
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 ); } }
第3步:使用Topshelf宿主我们的服务,主要是Topshelf如何设置我们的服务的配置和启动和停止的时候的方法调用
class Program { static void Main ( string [ ] args ) { HostFactory.Run ( x => { x.Service<MyClass> ( ( s ) => { s.SetServiceName ( "ser" ); 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" ); } ); } }
第4步: cmd命令
ConsoleApp_Topshelf.exe install (安装Windows服务)
ConsoleApp_Topshelf.exe uninstall (卸载Windows服务)
代码下载:http://files.cnblogs.com/aierong/ConsoleApp_Topshelf.rar