在异步WCF调用中,我该在哪里捕获EndpointNotFoundException?

4

我在测试中遇到了一些困难,无法捕获异常。实际上,我断开了服务以使终端点不可用,并尝试修改我的应用程序以处理这种情况。

问题是无论我在哪里放置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
            {
...

不行。有什么想法吗?
1个回答

2
我建议您使用IAsyncResult。当您在客户端生成WCF代理并获取异步调用时,应该会得到一个TopicServiceClient.BeginGetAllTopics()方法。该方法返回一个IAsyncResult对象。它还需要一个AsyncCallback委托在完成时调用。完成后,您调用EndGetAllTopics()并提供传递给EndGetAllTopics()的IASyncResult。
您可以在调用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"/>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接