Do I need to terminate Task in windows service in

2019-08-07 04:53发布

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?

2条回答
叼着烟拽天下
2楼-- · 2019-08-07 05:29

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.

查看更多
可以哭但决不认输i
3楼-- · 2019-08-07 05:33

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
查看更多
登录 后发表回答