C#,在 Windows 服务的 OnStart 中调用异步方法

C#, Calling async method inside OnStart of Windows service

我正在开发一个能够接收套接字连接的windows服务,所以在OnStart方法中:

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

start 函数如下所示:

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

问题是没有连接被接受,而同样的代码 运行 在标准命令行项目中完美,我怀疑我的设计有问题,哪个线程 运行 是 OnStart 方法?,当控制在 await 接受过程后返回到 OnStart 时,异步方法是否被忽略,因为它是 windows 服务中的特例?欢迎任何建议

当调用您的 start() 方法时,代码会立即继续并 OnStart 完成。现在您自己的代码中没有任何部分能够捕获任何异常。异常必须由 TaskScheduler 捕获。但这只会在等待任务或垃圾收集时发生。

所以基本上,您的代码可能会抛出一个 Exception,在 Task 被垃圾回收之前一直未被观察到。为了更快地捕获日志异常,请始终确保在任何地方都没有等待的方法中捕获异常:

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.
    } 
}

这似乎是 Windows 防火墙的问题,当我将我的代码作为控制台应用程序进行测试时,我收到了来自 Windows 防火墙的确认消息,要求获得打开端口的权限,但是当我将它作为一项服务进行测试时,防火墙在没有任何通知的情况下默默地阻止了传入连接。