简体   繁体   English

Task.Run包装的方法未捕获异常

[英]Exception not caught in Task.Run wrapped method

New to async await integration in C# 5. I'm working with some basic Task based methods to explore async await and the TPL. C#5中异步等待集成的新增功能。我正在使用一些基于任务的基本方法来探索异步等待和TPL。 In this example below I'm calling a web service with a timeout of 5 seconds. 在下面的示例中,我将调用超时为5秒的Web服务。 If the timeout expires it should throw an exception so I can return false from the method. 如果超时到期,它将引发异常,因此我可以从该方法返回false。 However, the timeout never occurs, or maybe it does but the Task never returns. 但是,超时永远不会发生,或者确实会发生,但是Task永远不会返回。

public static Task<bool> IsConnectedAsync()
{
    return Task.Run(() =>
    {
        try
        {
            using (WSAppService.AppService svc = new NCSoftware.Common.WSAppService.AppService(GetServiceUrl(WebService.app)){Timeout = 5000})
            {
                return svc.PingB();
            }
        }
        catch (Exception ex)
        {
            Logger.LogException(ex.Message, ex, "IsConnectedAsync");
        }    
        return false;
    });
}

If you could please help with how to properly handle this so that if the timeout occurs or even better, an exception occurs, the Task does return. 如果可以帮助您如何正确处理此问题,以便在发生超时甚至更好的情况下发生异常,则任务会返回。

In general, you shouldn't use Task.Run if you're wrapping async services. 通常,如果要包装async服务,则不应使用Task.Run Since this is a service reference, you should be able to expose an async method (returning Task ) directly from the service, in which case you could use: 由于这是服务参考,因此您应该能够直接从服务公开async方法(返回Task ),在这种情况下,您可以使用:

public async static Task<bool> IsConnectedAsync()
{
    try
    {
         using (WSAppService.AppService svc = new NCSoftware.Common.WSAppService.AppService(GetServiceUrl(WebService.app)){Timeout = 5000})
         {
              return await svc.PingBAsync();
         }
     }
     catch (Exception ex)
     {
         Logger.LogException(ex.Message, ex, "IsConnectedAsync");
     }    
     return false;
}

If you must wrap via Task.Run (again, this is not suggested, as it's turning synchronous code into async via the thread pool, which is typically better handled by the user at the top level), you could do: 如果必须通过Task.Run包装(同样,不建议这样做,因为它通过线程池将同步代码转换为异步代码,通常最好由顶级用户来处理),您可以执行以下操作:

public async static Task<bool> IsConnectedAsync()
{
    try
    {
       return await Task.Run(() =>
       {
         using (WSAppService.AppService svc = new NCSoftware.Common.WSAppService.AppService(GetServiceUrl(WebService.app)){Timeout = 5000})
         {
              return svc.PingB();
         }
       }
     }
     catch (Exception ex)
     {
         Logger.LogException(ex.Message, ex, "IsConnectedAsync");
         return false;
     }    
}

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

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