1

我收到如下错误

“通信对象 System.ServiceModel.Channels.ServiceChannel 无法用于通信,因为它处于故障状态。”

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();
}

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

有人能帮帮我吗?我尝试了堆栈中提到的一些方法,但没有找到解决方案。

4

1 回答 1

5

问题是使用...

简单的解决方案:

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();                  
        });

避免使用语句的问题

于 2012-05-17T20:26:57.453 回答