TopShelf-(01)控制台实例-Program

ゝ一纸荒年。 2024-02-17 18:26 148阅读 0赞

开发windows服务时,最麻烦的就是调试了,需要安装=》运行=》附加进程=》开始调试。修改代码后要重复以上步骤。
topshelf 允许使用控制台程序开发 windows服务,调试非常方便。就像调试控制台程序一样 F5 启动就OK了。
开发时我们可以大大节省调试时间,只需几行代码就可以开发出一个windows服务。

介绍:
topshelf是创建windows服务的一种方式,相比原生实现ServiceBase、Install.Installer更为简单方便,
我们只需要几行代码即可实现windows服务的开发。
topshelf相对原生来说,调试起来比较方便,可以在开发时以控制台的形式直接f5调试,发布时用命令以服务的形式部署。
还一个比较有用的特性是支持多实例的部署,这样可以在一台机器上部署多个相对的服务。

官网:http://topshelf-project.com/
源码:https://github.com/Topshelf/Topshelf/

实例代码:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Timers;
  6. using Topshelf;
  7. using TopshelfServiceRule;
  8. namespace TopshelfService
  9. {
  10. /*
  11. * Topshelf 框架安装服务常用命令
  12. * 安装:TopshelfService.exe install
  13. * 启动:TopshelfService.exe start
  14. * 停止:TopshelfService.exe stop
  15. * 卸载:TopshelfService.exe uninstall
  16. */
  17. class Program
  18. {
  19. static void Main(string[] args)
  20. {
  21. HostFactory.Run(x =>
  22. {
  23. //使用 TownCrier 类,配置服务事件
  24. x.Service<TownCrier>(s =>
  25. {
  26. //使用自定义的服务
  27. s.ConstructUsing(name => new TownCrier());
  28. //服务启动事件
  29. s.WhenStarted(tc => tc.Start());
  30. //服务停止后事件
  31. s.WhenStopped(tc => tc.Stop());
  32. //服务停止后继续运行时事件
  33. s.WhenContinued(tc => tc.Continued());
  34. //服务暂定事件
  35. s.WhenPaused(tc => tc.Paused());
  36. //服务卸载事件
  37. s.WhenShutdown(tc => tc.Shutdown());
  38. });
  39. #region 服务配置
  40. x.RunAsLocalSystem();
  41. #region 启动类型
  42. x.StartAutomatically();//自动运行
  43. //x.StartManually();//手动运行
  44. //x.StartAutomaticallyDelayed();//自动延迟运行
  45. //x.Disabled();//禁用
  46. #endregion
  47. #region 服务信息
  48. x.SetDescription("111 服务 111服务的描述");//描述
  49. x.SetDisplayName("111 显示名");//显示名称
  50. x.SetServiceName("111服务");//服务名称
  51. #endregion
  52. #endregion
  53. });
  54. }
  55. }
  56. //服务调用的类,其中的函数对应服务中的事件,如启动事件、暂停事件、恢复事件、继续运行事件等
  57. public class TownCrier
  58. {
  59. readonly Timer _timer;
  60. public TownCrier()
  61. {
  62. _timer = new Timer(1000) { AutoReset = true };
  63. _timer.Elapsed += (sender, eventArgs) =>
  64. {
  65. Console.WriteLine("It is {0} and all is well", DateTime.Now);
  66. Msg(string.Format("It is {0} and all is well", DateTime.Now));
  67. };
  68. }
  69. public void Start() { _timer.Start();Msg("已启动");}
  70. public void Stop() { _timer.Stop(); Msg("已停止"); }
  71. public void Continued() { Msg("继续运行"); }
  72. public void Paused() { Msg("已暂停"); }
  73. public void Shutdown() { Msg("已卸载"); }
  74. public void Msg(params string[] msg)
  75. {
  76. ServiceEvent.Msg(msg);
  77. if (msg != null)
  78. msg.All(x => { Console.WriteLine(x);return true; });
  79. }
  80. }
  81. }

发表评论

表情:
评论列表 (有 0 条评论,148人围观)

还没有评论,来说两句吧...

相关阅读

    相关 恋爱Program

    在内部论坛上看人帖出了这个,感觉很有意思。与大家一起分享一下。呵呵。。   result love(boy, girl)  \{ \-      if  ( bo