Do I need to terminate Task in windows service in OnStop method?

我怕爱的太早我们不能终老 提交于 2019-12-24 09:18:52

问题


So I have a Windows Service And I started task in 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
           }
       }

Do I need to add CancellationToken and stop Task in OnStop or it is unnecessary? Because when service will stop - Task stops as well. Does it safe or not?


回答1:


You're driving down the highway at 130 kmph. Suddenly you see a policeman who tells you to stop. When you notice him you are in point A. You can either:

  1. Ignore his command
  2. Stop instantaneously (in point A) changing the lane and crashing with a big explosion.
  3. Stop gradually but safely, decreasing the speed of your vehicle, and eventually reaching 0 kmph in point B. Point B is as close to point A as possible but as far as necessary as not to endanger anyone.

In real life anyone would choose 3). In .NET, depending on the nature and importance of your application you could choose 1) or 2) also.

It depends on you whether you want to risk:

  1. being chased by the police (killed by Task Manager)
  2. crashing (loose important data or cause inconsistencies and what not)
  3. absolutely nothing



回答2:


Tasks run as background threads. Thus, when the service stops, the task will be automatically stopped. Whether you need to formally cancel the task depends on whether the task needs to know it is exiting so that it can perform any necessary cleanup.



来源:https://stackoverflow.com/questions/15159457/do-i-need-to-terminate-task-in-windows-service-in-onstop-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!