简体   繁体   中英

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

在此输入图像描述

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM