C#, Calling async method inside OnStart of Windows service

主宰稳场 提交于 2021-01-27 21:18:45

问题


I am developing a windows service that is able to receive socket connection, so in the OnStart method:

protected override void OnStart(string[] args)
{
    start();
}

The start function looks like this:

public async void Start()
{
      //initialization things
      ...
      ...
      TcpListener listener = new TcpListener(IPAddress.Any, port);
      listener.Start();
      while(true)
      {
          TcpClient client = await listener.AcceptTcpClientAsync().ConfigureAwait(false);
          ...
      }
      ...    
}

The problem is that no connection is accepted, while same code run perfect in standard command line project, I doubt there is a problem in my design, which thread runs the OnStart method?, when control goes back to OnStart after awaiting the accept process, is the async method ignored as it is a special case in windows service? Any suggestions is welcomed


回答1:


When calling your start() method, the code instantly continues and OnStart completes. There is now no part of your own code that is able to catch any exceptions. Exceptions will have to be caught by the TaskScheduler. But this will only happen when the Task is awaited or garbage collected.

So basically, your code will have probably thrown an Exception that remains unobserved until the Task is garbage collected. In order to catch an log exceptions sooner, always make sure you catch exceptions inside the method that is not awaited anywhere:

protected override void OnStart(string[] args)
{
    Start();

    // This method finishes immediately (or at least after your first 
    // 'await' in the Start() method. That does not mean Start() runs 
    // on another thread however.
}

private async Task Start()
{
    try
    {
        //initialization things
        ...
        ...
        TcpListener listener = new TcpListener(IPAddress.Any, port);
        listener.Start();
        while(true)
        {
            TcpClient client = await listener.AcceptTcpClientAsync().ConfigureAwait(false);
            ...
        }
        ...   
    }
    catch (Exception ex)
    {
        // TODO: LOG! And probably stop the service too.
    } 
}



回答2:


It seems it is a problem in Windows firewall, when I test my code as a console application, I had a confirmation message from Windows firewall to ask for permission to open the port, but when I test it as a service, firewall silently blocked the incoming connections without any notification.



来源:https://stackoverflow.com/questions/54998693/c-calling-async-method-inside-onstart-of-windows-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!