C#,在Windows服务的OnStart中调用异步方法 [英] C#, Calling async method inside OnStart of Windows service

查看:93
本文介绍了C#,在Windows服务的OnStart中调用异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个能够接收套接字连接的Windows服务,因此在 OnStart 方法中:

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();
}

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服务中的一种特殊情况?欢迎任何建议

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

推荐答案

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

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.

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

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

这篇关于C#,在Windows服务的OnStart中调用异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆