通信对象System.ServiceModel.Channels.ServiceChannel不能用于通信,因为它处于Faulted状态

时间:2012-05-17 06:05:18

标签: c# .net wcf c#-4.0

我收到错误,如下所示

“通信对象System.ServiceModel.Channels.ServiceChannel不能用于通信,因为它处于Faulted状态。”

using (SecurityClient securityClient = new SecurityClient())
{                        
    SecurityService.GetIncomingPermissionsByIdRequest securityRequest =
        new GetIncomingPermissionsByIdRequest(Convert.ToInt32(recordId));
    SecurityService.GetIncomingPermissionsByIdResponse securityResponse =
        securityClient.GetIncomingPermissionsById(securityRequest);
    incomingPermissions = securityResponse.GetIncomingPermissionsByIdResult;
    SetPermissionFields();
    SetPermissionList();                  
    securityClient.Close();
}

在上面的代码中,我能够发送请求,但是当涉及到响应行并尝试获得响应时,它会转到故障状态并得到上面提到的错误。我已经检查了SecurityClient在移动之前的状态到响应行,然后它处于创建状态。但是当试图获得响应时,它会转移到故障状态。

请问任何人帮助我。我已经尝试了堆栈中提到的一些方法,但没有找到解决方案。

1 个答案:

答案 0 :(得分:4)

问题在于使用......

简单的解决方案:

SecurityClient securityClient = new SecurityClient();

SecurityService.GetIncomingPermissionsByIdRequest securityRequest = new GetIncomingPermissionsByIdRequest(Convert.ToInt32(recordId));
SecurityService.GetIncomingPermissionsByIdResponse securityResponse = securityClient.GetIncomingPermissionsById(securityRequest);
incomingPermissions = securityResponse.GetIncomingPermissionsByIdResult;
SetPermissionFields();
SetPermissionList();                  
securityClient.Close();
securityClient.Dispose();

更优雅的解决方案:

创建WCF扩展:

using System;
using System.ServiceModel;

namespace MyNamespace
{
    public static class WcfExtensions
    {
        public static void Using<T>(this T client, Action<T> work)
            where T : ICommunicationObject
        {
            try
            {
                work(client);
                client.Close();
            }
            catch (CommunicationException e)
            {
                client.Abort();
            }
            catch (TimeoutException e)
            {
                client.Abort();
            }
            catch (Exception e)
            {
                client.Abort();
                throw;
            }          
        }
    }
}

然后使用以下语法进行实例化:

    new SecurityClient().Using(securityClient => 
        {
            SecurityService.GetIncomingPermissionsByIdRequest securityRequest = new GetIncomingPermissionsByIdRequest(Convert.ToInt32(recordId));
            SecurityService.GetIncomingPermissionsByIdResponse securityResponse = securityClient.GetIncomingPermissionsById(securityRequest);
            incomingPermissions = securityResponse.GetIncomingPermissionsByIdResult;
            SetPermissionFields();
            SetPermissionList();                  
        });

Avoiding Problems with the Using Statement