Beau Johnny Bekkestad
Beau Johnny Bekkestad

Reputation: 381

Windows service won't stop

I've made this small program that has an interesting behavior that i cannot get around. The idea is for this to act like a scheduler, it will execute a command after a specific time has passed. Everything works as intended, but when i went to shutdown the service i realized a few things. 1. The service takes a long time to shutdown. Sometime more than 30 minutes, I've had to kill the PID as well. 2. The longer the service has been running the longer it takes to shutdown. I'm thinking it has something to do with the number of times the command has been executed. 3. I think that the shorter the interval is between each iteration the easier it is to shutdown the service.

Here is the code i am using.

public void Start()
{
    _cancellationToken = new CancellationTokenSource();
    var token = _cancellationToken.Token;

    _pollingTask = Task.Factory.StartNew(
        () =>
        {
            while (true)
            {
                try
                {
                    Log.Debug("Call Import PDF");
                    ConnectUncPaths();
                    ImportPdf();
                    Thread.Sleep(Intervall * 60000);
                    if (token.IsCancellationRequested)
                        break;
                }
                catch (Exception)
                {
                    DissconnectUncPaths();
                }
            }
        }, token, TaskCreationOptions.LongRunning, TaskScheduler.Current);
    }

    public void Stop()
    {
        _cancellationToken.Cancel();
        _pollingTask.Wait();
}

And here is a screenshot

enter image description here

Upvotes: 1

Views: 1094

Answers (1)

Dennisch
Dennisch

Reputation: 7533

It won't stop because Thread.Sleep will not end until its delay is up. Instead, try something like this:

public void Start()
{
    _cancellationToken = new CancellationTokenSource();
    var token = _cancellationToken.Token;

    _pollingTask = Task.Factory.StartNew(
        () =>
        {
            while (!token.IsCancellationRequested)
            {
                try
                {
                    Log.Debug("Call Import PDF");
                    ConnectUncPaths();
                    ImportPdf();
                    Task.Delay(TimeSpan.FromMinutes(Intervall), token)
                }
                catch (Exception)
                {
                    DissconnectUncPaths();
                    break;
                }
            }
        }, token, TaskCreationOptions.LongRunning, TaskScheduler.Current);
}

Upvotes: 4

Related Questions