我是否需要在OnStop方法中终止Windows服务中的任务?

And*_*ich 1 c# windows-services task-parallel-library

所以我有一个Windows服务我开始在OnStart上完成任务

   partial class AppServices : ServiceBase
    {
        private static readonly ILog Log = LogManager.GetCurrentClassLogger();
        private Task _task;

        public AppServices()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            Log.Info("Service started");

            _task = Task.Factory.StartNew(StartWork, TaskCreationOptions.LongRunning);
        }

        protected override void OnStop()
        {
            Log.Info("Service stopped");
        }

        private void StartWork()
        {
           while(true)
           {
               // grab some data from db or services
           }
       }
Run Code Online (Sandbox Code Playgroud)

我是否需要在OnStop中添加CancellationToken并停止任务,否则是不必要的?因为当服务停止时 - 任务也会停止.它安全与否?

Edu*_*tru 11

你以130公里的速度沿着高速公路行驶.突然间你看到一个叫你停下来的警察.当你注意到他时你就在A点.你可以:

  1. 忽略他的命令
  2. 立即停止(在A点)改变车道并在大爆炸时坠毁.
  3. 逐渐但安全地停止,降低车速,最终在B点达到0公里.B点尽可能接近A点,但必要时尽可能不危及任何人.

在现实生活中,任何人都会选择3).在.NET中,根据应用程序的性质和重要性,您也可以选择1)或2).

取决于您是否要冒险:

  1. 被警察追捕(被任务经理杀害)
  2. 崩溃(松散的重要数据或导致不一致,什么不是)
  3. 绝对没有