1

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
  • OnStop() allows you to do cleanup or persitency-things, if neccessary. Your Service will be shutdown afterwards (or after 30 seconds, if you are not ready until then).
    – TGlatzer
    Commented Mar 1, 2013 at 13:57

2 Answers 2

12

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
1
  • Your answer and the analogy is so well put. Thank you on behalf of other SO users as well ;), gave you a plus one as well...
    – Sizons
    Commented Jun 20, 2016 at 12:25
4

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.

5
  • Also, it depends on whether the task can leave anything in a corrupted state if it is terminated midstream. Commented Mar 1, 2013 at 14:10
  • That's what is meant by any necessary cleanup - releasing unmanaged resources, closing files, closing database connections, etc.
    – Matt Davis
    Commented Mar 1, 2013 at 14:12
  • 1
    Data consistency is more than just resource cleanup. For example, the task might move an item from one DB to another. (1) Open DB connection, delete item, close DB connection. (2) Open second DB, add item, close DB connection. Between (1) and (2) all resources are cleaned up, but you have corrupt data (you lost an item). Commented Mar 1, 2013 at 14:16
  • I'm sure "etc" includes performing "the last 'half' of a 'transaction' which has been executed midway" or, if possible, "rolling back the first 'half' of such a 'transaction'" should that be possible. Unmanaged resources, files and database connections are actually closed automatically and if we consider RDBMSs something "godly" which don't care if you disconnect abruptly or gracefully whatsoever and we completely exclude shared unmanaged objects (sharedmem, common mutexes) that are logically offered by this service, then you really don't need to release unmanaged resources at all. Commented Mar 1, 2013 at 14:20
  • In my previous comment I was refering to the comment @MattDavis wrote... And it was a "positive question mark" Commented Mar 1, 2013 at 14:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.