欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

C#实现TopShelf服务的创建与启动

最编程 2024-08-08 21:43:29
...
1 public class TownCrier 2 { 3 readonly Timer _timer; 4 public TownCrier() 5 { 6 _timer = new Timer(1000) { AutoReset = true }; 7 _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} and all is well", DateTime.Now); 8 } 9 public void Start() { _timer.Start(); } 10 public void Stop() { _timer.Stop(); } 11 } 12 public class Program 13 { 14 15 16 public static void Main(string[] args) 17 { 18 //配置和运行宿主服务 19 HostFactory.Run(x => //1 20 { 21 22 x.Service<TownCrier>(s => //2 23 { 24 //指定服务类型 25 s.ConstructUsing(name => new TownCrier()); //3 26 //当服务启动后执行 27 s.WhenStarted(tc => tc.Start()); //4 28 //当服务停止后执行 29 s.WhenStopped(tc => tc.Stop()); //5 30 }); 31 //服务通过本地系统账号裕兴 32 x.RunAsLocalSystem(); //6 33 //服务信息描述 34 x.SetDescription("Sample Topshelf Host"); //7 35 //服务显示名称 36 x.SetDisplayName("MyTopShelfShowName"); //8 37 //服务名称 38 x.SetServiceName("MyTopShelfName"); //9 39 }); 40 } 41 }

推荐阅读