【问题标题】:why operations scheduled to be executed on thread pool asynchronously don't throw exception when scheduled为什么计划在线程池上异步执行的操作在计划时不会抛出异常
【发布时间】:2015-02-10 14:01:31
【问题描述】:

我正在使用 Web 服务来获取长数组中的一些结果,如下所示:

      try
      {

            System.Threading.ThreadPool.QueueUserWorkItem((o) =>
            {
                byte[] result = (new MagfaGetMessages()).getMessages(false,SMSUseProxy,SMSProxyAddress,SMSProxyUserName,SMSProxyPassword,1000);
            });
            }
        }

        catch
        {
            SMSwebServiceFailed = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:ff");
        }



// GetMessage Class

         public MAGFAWebService.DatedCustomerReturnIncomingFormat[] getMessages(Boolean useProxy, String proxyAddress, String proxyUsername, String proxyPassword, String username, String password, String domain, int numberOfMessages)
    {
        lock (MagfaLock)
        {
            MAGFAWebService.SoapSmsQueuableImplementationService sq = new MAGFAWebService.SoapSmsQueuableImplementationService();

            if (useProxy)
            {
                WebProxy proxy;
                proxy = new WebProxy(proxyAddress);
                proxy.Credentials = new NetworkCredential(proxyUsername, proxyPassword);
                sq.Proxy = proxy;
            }
            sq.Credentials = new System.Net.NetworkCredential(username, password);
            sq.PreAuthenticate = true;

            return (MAGFAWebService.DatedCustomerReturnIncomingFormat[])sq.getMessages(domain, numberOfMessages);
        }

    }

但有时我会收到此错误:

The request failed with HTTP status 504: Gateway Time-out.

我在代码中使用了 try{} catch,我想知道为什么会出现错误以及为什么它没有被捕获?

错误将出现在这一行:

  MAGFAWebService.DatedCustomerReturnIncomingFormat[])sq.getMessages(domain, numberOfMessages

感谢您的帮助。

【问题讨论】:

    标签: c#


    【解决方案1】:

    504: Gateway Time-out 表示您可以连接到主机,但由于某种原因连接超时。原因可能是主机本身、其代理、DNS 设置或连接问题。有类似的问题在:Difference between operation has time out and (504) Gateway Timeout

    【讨论】:

    • 请注意,帖子中的信息虽然正确,但与问题完全无关 - “为什么计划在线程池上异步执行的操作在计划时不会抛出异常(在开始操作之前)?”。
    • 所以它不会因为线程池而引发 cthrow 异常? @AlexeiLevenkov
    【解决方案2】:

    示例中的 Try/catch 捕获在调用 ThreadPool.QueueUserWorkItem 期间发生的异常,仅此而已。人们可以期待“null 作为队列项传递”或假设“池中空间不足”之类的东西,但计划操作引发的异常不会出现在该 try/catch 块中。

    其中一个原因是在该 try/catch 块完成后的一段时间内操作甚至可能无法启动。

    修复 - 异步操作本身的 try/catch。

    或者 - 使用新的async/await 允许您编写看起来同步的异步代码:

    try {
       var message = await GetMessagesAsync();
    }
    catch (Exception ex) {
      LogException(ex); 
    }
    
    async Task<IEnumerable<Message>> GetMessagesAsync() {....}
    

    【讨论】:

    • 我知道发生了什么以及为什么 try/catch 有效。但是你能解释一下我该如何解决这个问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多