简体   繁体   English

服务窗口中的方法OnStop如何延迟?

[英]how delay on method OnStop in service windows?

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. 我有一个Windows服务,该服务正在使用API​​,该API每次启动时都会将数据发送到API,并且在禁用该服务时,需要将此信息用于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. 我使用的是Thread,但是它不遵守确定的时间,因此它没有时间向它发送有关该服务已针对API停止的信息。

How can I delay the service stop and allow time for the data to arrive in the API? 如何延迟服务停止并让数据有时间到达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;
        }
    }

I solved the problem using the "Thread.Sleep ();" 我使用“ 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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