Async worker for a Windows Service

Sample for a Windows Service using Task’s

    public class WinServiceBiz
    {
        //https://msdn.microsoft.com/en-us/library/dd997396(v=vs.110).aspx

        private static bool _stateRunning = false;
        private static CancellationTokenSource _tokenSource;
        private Task t;
        private CancellationToken token;

        //The worker
        public async Task<bool> DoWork(CancellationToken token)
        {
            Debug.WriteLine("DoWork() 1");

            // Were we already canceled?
            token.ThrowIfCancellationRequested();

            while (!token.IsCancellationRequested)
            {
                Debug.WriteLine("DoWork() 2");
                await Task.Delay(1000); //Simulate work

                //time to stop?
                if (token.IsCancellationRequested)
                {
                    Debug.WriteLine("Task cancelled");
                    _stateRunning = false;
                }
            }
            return true; //avoiding async void
        }

        public void OnStart(string[] args)
        {

            if (! _stateRunning)
            {
                Debug.WriteLine("OnStart()");
                _stateRunning = true;
                _tokenSource = new CancellationTokenSource();
                token = _tokenSource.Token;

                try
                {
                    // Request cancellation of a single task when the token source is canceled. 
                    // Pass the token to the user delegate, and also to the task so it can  
                    // handle the exception correctly.
                    t = Task.Factory.StartNew(() => DoWork(token), token);
                    Debug.WriteLine("Task {0} executing", t.Id);
                    t.Wait(); //start task and don't await task to finish
                }
                catch (Exception e)
                {
                    //Expecting 
                    Debug.WriteLine("OnStart - Exception: {0}", e.GetType().Name);
                }
                finally
                {
                    Debug.WriteLine("OnStart - finally");
                } 
            }

        }

        public void OnStop()
        {
            Debug.WriteLine("OnStop()");

            if (_stateRunning)
            {
                //SetDoStop
                try
                {
                    if (_tokenSource != null)
                    {
                        _tokenSource.Cancel();
                        Debug.WriteLine("Task cancellation requested.");

                    }
                }
                catch (Exception e)
                {
                    //Expecting 
                    Debug.WriteLine("OnStop - Exception: {0}", e.GetType().Name);
                }
                finally
                {
                    Debug.WriteLine("OnStop - finally");
                    if (_tokenSource != null)
                    {
                        _tokenSource.Dispose();
                        Debug.WriteLine("_tokenSource.Disposed");
                    }
                }
            }
        }

    }

https://msdn.microsoft.com/en-us/library/dd997396(v=vs.110).aspx

The End.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: