【问题标题】:Unable to catch Webservice call method within try catch block无法在 try catch 块中捕获 Webservice 调用方法
【发布时间】:2014-04-01 13:10:59
【问题描述】:

我正在开发一个 WP8 应用程序。我在外部系统上创建了一个 Web 服务,然后在我的应用程序中调用这些 Web 服务方法:

ServiceReference1.WebServiceClient ws = new WebServiceClient();
try
{
 ws.FetchInboxAsync(EmailId);
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}

现在,如果服务器关闭,我希望控件进入 catch 块,但它没有,我得到以下异常:

“System.ServiceModel.CommunicationException”类型的异常 发生在 System.ServiceModel.ni.dll 中但未在用户中处理 代码。

我确实意识到 web 服务调用方法是异步的,所以它的异常不会被 try catch 捕获。在论坛上,人们建议使用 await 关键字。但是当我写

等待 ws.FetchInboxAsync(EmailId);

我收到一个错误:无法等待 void。

我尝试了答案here 中提到的一些东西,但我仍然得到同样的异常

【问题讨论】:

    标签: c# web-services windows-phone-8 async-await


    【解决方案1】:

    您可以订阅 FetchInboxCompleted 事件:

    ServiceReference1.WebServiceClient ws = new WebServiceClient();
    ws.FetchInboxCompleted += new EventHandler<ServiceReference1.FetchInboxCompletedEventArgs>(c_FetchInboxCompleted);
    ws.FetchInboxAsync(EmailId);
    

    在事件处理程序中,检查结果:

    static void c_FetchInboxCompleted(object sender, serviceReference1.FetchInboxCompletedEventArgs e)
    {
         // check e.Error which contains the exception, if any
    }
    

    【讨论】:

    • 我尝试了您的建议,但在控件进入事件处理程序之前,相同的未处理异常(我在问题中提到)停止执行并使应用程序崩溃。我想要的是我应该能够保护应用程序免受这种情况的影响,而是弹出一些消息,例如服务器当前不可用。
    【解决方案2】:

    如果自动生成的 WCF 客户端代理支持它,您应该能够等待以 TaskAsync 结尾的方法:

    await ws.FetchInboxTaskAsync(EmailId);
    

    如果自动生成的WCF客户端代理没有定义这个方法,那么你可以自己定义as described on MSDN:

    public static Task FetchInboxTaskAsync(this ServiceReference1.WebServiceClient client, string emailId)
    {
      return Task.Factory.FromAsync(client.BeginFetchInbox, client.EndFetchInbox, emailId, null);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 2017-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-22
      相关资源
      最近更新 更多