Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#,在Windows服务的OnStart内调用异步方法_C#_Asynchronous_Async Await_Windows Services - Fatal编程技术网

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

C#,在Windows服务的OnStart内调用异步方法,c#,asynchronous,async-await,windows-services,C#,Asynchronous,Async Await,Windows Services,我正在开发一个能够接收套接字连接的windows服务,因此在OnStart方法中: protected override void OnStart(string[] args) { start(); } start函数如下所示: public async void Start() { //initialization things ... ... TcpListener listener = new TcpListener(IPAddre

我正在开发一个能够接收套接字连接的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
时,哪个线程运行
OnStart
方法,异步方法在windows服务中是一种特殊情况,因此是否被忽略?欢迎任何建议

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

因此,基本上,您的代码可能抛出了一个
异常
,该异常在
任务
被垃圾收集之前一直未被发现。为了更快地捕获日志异常,请始终确保捕获方法中未在任何地方等待的异常:

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防火墙的确认消息,要求获得打开端口的权限,但当我将其作为服务进行测试时,防火墙会在没有任何通知的情况下无声地阻止传入的连接

很可能是未捕获的异常导致服务失败,因为不会捕获任何异常。查看任务调度器。未观察到的任务异常,检查事件日志并刷新服务屏幕。检查事件日志后,没有未观察到的异常:(将方法的签名更改为
异步任务
,然后重试。哦,请阅读以下内容:A)不要使用async void,B)记录任何未观察到的异常,C)在提交服务之前尝试在控制台应用程序中运行此功能,因为它更易于调试,尽管这不是我的问题,这个答案帮助我改进了代码,谢谢你仍然没有异常记录?