5

我有一个遇到问题的 WCF 客户端。
我不时收到此异常:Cannot access a disposed object. 这就是我打开连接的方式:

private static LeverateCrmServiceClient crm = null;

public static CrmServiceClient Get(string crmCertificateName)
        {

            if (crm != null)
            {
                crm.Close();
            }
            try 
            {
                crm = new LeverateCrmServiceClient("CrmServiceEndpoint");
                crm.ClientCredentials.ClientCertificate.SetCertificate(
                               StoreLocation.LocalMachine,
                               StoreName.My,
                               X509FindType.FindBySubjectName,
                               crmCertificateName);
            }
            catch (Exception e) 
            {
                log.Error("Cannot access CRM ", e);
                throw;
            }
            return crm;
        }

如您所见,我每次都在关闭并重新打开连接。你认为可能是什么问题?

堆:

System.ServiceModel.Security.MessageSecurityException: Message security verification failed. ---> System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.ServiceModel.Security.SymmetricSecurityProtocol'.
  at System.ServiceModel.Channels.CommunicationObject.ThrowIfClosedOrNotOpen()
  at System.ServiceModel.Security.MessageSecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates)
  --- End of inner exception stack trace ---

Server stack trace:
  at System.ServiceModel.Security.MessageSecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates)
  at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
  at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
  at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
  at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
  at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:
  at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
  at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
  at Externals.CrmService.ICrmService.GetTradingPlatformAccountDetails(Guid ownerUserId, String organizationName, String businessUnitName, Guid tradingPlatformAccountId)
  at MyAppName.Models.ActionsMetadata.Trader.BuildTrader(Guid tradingPlatformAccountId) in C:\Users\X\Documents\Visual Studio 2010\Projects\MyAppName\MyAppName\Models\ActionsMetadata\Trader.cs:line 120
  at MyAppName.Models.ActionsMetadata.Trader.Login(String accountNumber, String password) in C:\Users\X\Documents\Visual Studio 2010\Projects\MyAppName\MyAppName\Models\ActionsMetadata\Trader.cs:line 48
  at MyAppName.Models.ActionsMetadata.Handlers.LoginHandler.Handle(StepHandlerWrapper wrapper) in C:\Users\X\Documents\Visual Studio 2010\Projects\MyAppName\MyAppName\Models\ActionsMetadata\Handlers\LoginHandler.cs:line 23
  at MyAppName.Models.ActionsMetadata.Handlers.HandlerInvoker.Invoke(IAction brokerAction, ActionStep actionStep, Dictionary`2 stepValues, HttpContext httpContext, BaseStepDataModel model) in C:\Users\X\Documents\Visual Studio 2010\Projects\MyAppName\MyAppName\Models\ActionsMetadata\Handlers\StepServerInoker.cs:line 42
  at MyAppName.Controllers.LoginController.Login(String step) in C:\Users\X\Documents\Visual Studio 2010\Projects\MyAppName\MyAppName\Controllers\LoginController.cs:line 35
  at lambda_method(Closure , ControllerBase , Object[] )
  at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
  at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
  at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
  at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
  at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
  at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
4

1 回答 1

7

根据该堆栈跟踪,我假设您有一个 ASP.NET MVC 应用程序,其中包含一些调用该Get方法以获取CrmServiceClient对象的代码,然后继续调用该CrmServiceClient对象上的各种方法。例如,登录过程的一部分就是这样做的。

您的Get方法的工作方式是,每次调用它时,它都会首先关闭CrmServiceClient它之前返回的对象(无论它是否仍在使用)然后创建并返回一个新对象。

想象一下,两个用户几乎在同一时间尝试登录到您的应用程序——彼此相差几毫秒。处理第一个用户登录的线程调用Get并获取它的CrmServiceClient对象,然后一毫秒后处理第二个用户的登录调用Get的线程,这导致第一个线程的CrmServiceClient对象被关闭。但是,第一个线程仍在运行,现在当它尝试调用它的CrmServiceClient对象上的方法时,它会得到一个System.ObjectDisposedException: Cannot access a disposed object.

“如你所见,我每次都在关闭和重新打开连接。”

当前Get方法中的代码不是实现此目标的好方法。相反,您应该让调用者负责关闭(或处置)CrmServiceClient对象,并且您可能应该将您的Get方法重命名为OpenCreate建议这样做。无论发生任何异常,调用者都应使用using语句确保对象已关闭/处置:

using (CrmServiceClient client = CrmServiceFactory.Get("my-crm-certificate"))
{
    client.Something();
    client.GetTradingPlatformAccountDetails();
    client.SomethingElse();
} // client is automatically closed at the end of the 'using' block
于 2012-04-04T13:29:01.520 回答