【问题标题】:Where do I catch an EndpointNotFoundException for an Async WCF call?我在哪里可以捕获异步 WCF 调用的 EndpointNotFoundException?
【发布时间】:2011-04-24 13:33:57
【问题描述】:

我在测试期间难以捕获异常。我实际上断开了服务,因此端点不可用,我正在尝试修改我的应用程序以处理这种可能性。

问题是,无论我将 try/catch 块放在哪里,我似乎都无法在它未被处理之前捕捉到它。

我已经尝试将我的创建代码都包装在 try/catch 中,

this.TopicServiceClient = new KeepTalkingServiceReference.TopicServiceClient();
            this.TopicServiceClient.GetAllTopicsCompleted += new EventHandler<KeepTalkingServiceReference.GetAllTopicsCompletedEventArgs>(TopicServiceClient_GetAllTopicsCompleted);
             this.TopicServiceClient.GetAllTopicsAsync();

以及在服务调用完成时被调用的委托。

public void TopicServiceClient_GetAllTopicsCompleted(object sender, KeepTalkingServiceReference.GetAllTopicsCompletedEventArgs e)
        {
            try
            {
...

没有骰子。有什么想法吗?

【问题讨论】:

    标签: c# silverlight wcf exception-handling windows-phone-7


    【解决方案1】:

    我建议您使用 IAsyncResult。当您在客户端生成 WCF 代理并获取异步调用时,您应该获取一个 TopicServiceClient.BeginGetAllTopics() 方法。此方法返回一个 IAsyncResult 对象。它还需要在完成时调用 AsyncCallback 委托。完成后,您调用 EndGetAllTopics() 提供 IASyncResult(传递给 EndGetAllTopics()。

    您在对 BeginGetAllTopics() 的调用周围放置了一个 try/catch,它应该会捕获您所追求的异常。如果远程发生异常,即您确实进行了连接,但服务会引发异常,该异常在您调用 EndGetAllTopics() 时进行处理。

    这是一个非常简单的示例(显然不是生产)来演示我在说什么。这是用 WCF 4.0 编写的。

    namespace WcfClient
    {
    class Program
    {
        static IAsyncResult ar;
        static Service1Client client;
        static void Main(string[] args)
        {
            client = new Service1Client();
            try
            {
                ar = client.BeginGetData(2, new AsyncCallback(myCallback), null);
                ar.AsyncWaitHandle.WaitOne();
                ar = client.BeginGetDataUsingDataContract(null, new AsyncCallback(myCallbackContract), null);
                ar.AsyncWaitHandle.WaitOne();
            }
            catch (Exception ex1)
            {
                Console.WriteLine("{0}", ex1.Message);
            }
            Console.ReadLine();
        }
        static void myCallback(IAsyncResult arDone)
        {
            Console.WriteLine("{0}", client.EndGetData(arDone));
        }
        static void myCallbackContract(IAsyncResult arDone)
        {
            try
            {
                Console.WriteLine("{0}", client.EndGetDataUsingDataContract(arDone).ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0}", ex.Message);
            }
        }
    }
    }
    

    为了将服务器端异常传播回客户端,您需要在服务器 Web 配置中设置以下内容...

    <serviceDebug includeExceptionDetailInFaults="true"/>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      • 2011-05-12
      • 2015-08-19
      • 2014-04-29
      相关资源
      最近更新 更多