c# – 我在哪里捕获异步WCF调用的EndpointNotFoundException?

我在测试过程中遇到了一些异常.我实际上断开了服务,以便端点不可用,我试图修改我的应用程序来处理这种可能性.

问题是,无论我把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
            {
...

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

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

你在tryGetAllTopics()的调用周围放了一个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"/>
点赞