出现故障后重用 WCF 中的客户端类 [英] Reuse a client class in WCF after it is faulted

查看:21
本文介绍了出现故障后重用 WCF 中的客户端类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 WCF 作为客户端服务器系统.当我在服务器上添加对 IService 的服务引用时,会生成一个代理类 ServiceClient.我的代码如下所示:

I use WCF for a client server system. When I add a service reference to IService on the server, a proxy class ServiceClient is generated. My code looks like the following:

ServiceClient client = new ServiceClient();
try
{
    client.Operation1();
}
catch(Exception ex)
{
    // Handle Exception
}
try
{
    client.Operation2();
}
catch(Exception ex)
{
    // Handle Exception
}

问题是,如果第一次调用出现通信异常,客户端状态变为Faulted,不知道如何重新打开进行第二次调用.有办法重新打开吗?或者我应该创建一个新的并替换实例(这似乎不是一种优雅的方式)?

The problem is that if there is a communication exception in the first call, the client's state changes to Faulted, and I don't know how to reopen it to make the second call. Is there a way to reopen it? or should I create a new one and replace the instance (It doesn't seem like an elegant way)?

推荐答案

一旦 ICommunicationObject(您的 WCF 客户端对象)处于故障状态,重新打开"它的唯一方法就是创建一个新的.

Once a an ICommunicationObject (your WCF client object) is in a faulted state, the only way to "re-open" it is to create a new one.

ServiceClient client = new ServiceClient();
try
{
    client.Operation1();
}
catch(Exception ex)
{
    if (client.State == CommunicationState.Faulted)
    {
            client.Abort();
            client = new ServiceClient();
    }
}
try
{
    client.Operation2();
}
catch(Exception ex)
{
   // Handle Exception
}

这篇关于出现故障后重用 WCF 中的客户端类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆