1

I have a windows service that is consuming an API that every time it starts, it sends data to the API and when the service is disabled this information needs to be taken to the API. I'm using Thread, however it does not respect the time it was determined, so it does not give time for it to send information that the service was stopped for API.

How can I delay the service stop and allow time for the data to arrive in the API?

protected override void OnStart(string[] args)
    {
        _writeFile.Log("Foi iniciado o serviço");

        _shutdownEvent = new ManualResetEvent(false);
        _thread = new Thread(async () => await ControlSendHistorico());
        _thread.Start();

        base.OnStart(args);
    }

    protected override void OnStop()
    {
        if (_stopping) return;
        try
        {
            _stopping = true;
            _shutdownEvent.Set();
            //_shutdownEvent.WaitOne(30000);
            _thread.Join(30000);


            _writeFile.Log("O serviço foi parado");
            base.OnStop();
        }
        catch (Exception e)
        {
            _writeFile.Log("Falha ao parar o serviço " + e.Message);
        }
        finally
        {
            _stopping = false;
        }
    }
  • Please share the implementation of `ControlSendHistorico()` method. – KatariaA Mar 13 '19 at 13:16
  • 1
    Call [`RequestAdditionalTime`](https://learn.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicebase.requestadditionaltime?view=netframework-4.7.2)? – stuartd Mar 13 '19 at 13:17
  • What have you tried? See for example https://stackoverflow.com/questions/22534330/windows-service-onstop-wait-for-finished-processing, https://stackoverflow.com/questions/13454054/what-is-the-maximum-time-windows-service-wait-to-process-stop-request-and-how-to/29928342, and so on – CodeCaster Mar 13 '19 at 13:19
  • @stuartd I used this method, but it did not solve the problem – Fabrícia Santos Mar 14 '19 at 11:55
  • And when the power goes out and the computer loses power? You should never try to do anything time consuming during stop-type actions - you're never guaranteed you'll get the time to do so. Better to re-engineer so that you can perform some kind of *recovery* during the next start, when you expect to have as much time as you reasonably might need. – Damien_The_Unbeliever Mar 14 '19 at 11:59

1 Answers1

0

I solved the problem using the "Thread.Sleep ();" It does lock the main Thread of the service and not the middle one like I was doing.

protected override void OnStop()
{
    if (_stopping) return;
    try
    {
        _stopping = true;
        _shutdownEvent.Set();
        Thread.Sleep(500);

        _writeFile.Log("O serviço foi parado");
        base.OnStop();
    }
    catch (Exception e)
    {
        _writeFile.Log("Falha ao parar o serviço " + e.Message);
    }
    finally
    {
        _stopping = false;
    }
}