Объект связи не может быть использован для связи, потому что он был прерван - PullRequest
5 голосов
/ 12 ноября 2009

У меня есть пример проекта WCF, в котором воспроизводится проблема, связанная с моим настоящим приложением WCF. Вы можете скачать исходный код моего примера приложения WCF здесь

В соответствии с таймаутами, установленными в коде и конфигурационных файлах, я не понимаю, что происходит:

**** Server exception : System.ServiceModel.CommunicationObjectAbortedException: 

The communication object, System.ServiceModel.Security.SecuritySessionServerSettings+SecurityReplySessionChannel, cannot be used for communication because it 
has been Aborted.

   at System.ServiceModel.Channels.CommunicationObject.ThrowIfClosedOrNotOpen()
   at System.ServiceModel.Security.SecuritySessionServerSettings.ServerSecuritySessionChannel.SecureApplicationMessage(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState)
   at System.ServiceModel.Security.SecuritySessionServerSettings.SecuritySessionRequestContext.OnReply(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.RequestContextBase.Reply(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.RequestContextBase.Reply(Message message)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.Reply(MessageRpc& rpc)

**** client exception : : System.ServiceModel.Security.MessageSecurityException: An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail. ---> System.ServiceModel.FaultException: The message could not be processed. This is most likely because the action 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT/Cancel' is incorrect or because the message contains an invalid or expired security context token or because there is a mismatch between bindings. The security context token would be invalid if the service aborted the channel due to inactivity. To prevent the service from aborting idle sessions prematurely increase the Receive timeout on the service endpoint's binding.
   --- End of inner exception stack trace ---

Server stack trace: 
   at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecuritySessionChannel.ProcessRequestContext(RequestContext requestContext, TimeSpan timeout, SecurityProtocolCorrelationState correlationState)
   at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecuritySessionChannel.ReceiveInternal(TimeSpan timeout, SecurityProtocolCorrelationState correlationState)
   at System.ServiceModel.Security.SecuritySessionClientSettings`1.SecurityRequestSessionChannel.CloseOutputSession(TimeSpan timeout)
   at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecuritySessionChannel.CloseSession(TimeSpan timeout, Boolean& wasAborted)
   at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecuritySessionChannel.OnClose(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Close(TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.OnClose(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Close(TimeSpan timeout)

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 System.ServiceModel.ICommunicationObject.Close(TimeSpan timeout)
   at System.ServiceModel.ClientBase`1.System.ServiceModel.ICommunicationObject.Close(TimeSpan timeout)
   at System.ServiceModel.ClientBase`1.Close()
   at System.ServiceModel.ClientBase`1.System.IDisposable.Dispose()
   at WindowsFormsApplication1.Program.Main() in C:\Users\sdoucet\Documents\Visual Studio 2008\Projects\TestWCFLongExecution\WindowsFormsApplication1\Program.cs:line 25

Ответы [ 3 ]

7 голосов
/ 07 июня 2011

У нас была похожая проблема, потому что пул приложений, в котором размещена служба, был настроен так, чтобы Максимальное количество рабочих процессов было больше 1. Для успешного вызова Abort или Close его необходимо направить в тот же экземпляр службы, который обработал исходный запрос.

2 голосов
/ 06 января 2012

У меня была похожая проблема, когда я выполнял асинхронный вызов службы wcf. После получения результата в методе async_completed я получил исключение.

"Во время операции возникла исключительная ситуация, в результате чего результат стал недействительным. Проверьте исключение InnerException"

InnerException:
«Объект связи не может быть использован для связи, потому что он был прерван»

После долгих усилий найти решение, просто перехватить исключение, не выбрасывая метод async_completed. (то есть реализовал попытку / поймать). Я не понял, в чем именно проблема, но каким-то образом канал связи ломается.

Я попробовал вышеуказанный подход по следующей ссылке

http://geekswithblogs.net/SoftwareDoneRight/archive/2008/05/23/clean-up-wcf-clients--the-right-way.aspx

Тем не менее я не уверен, что это правильный подход, но в соответствии с моим сценарием с результатом операции я ничего не делаю дальше. Так что ловит исключение и останавливает сервис.

1 голос
/ 12 ноября 2009

Похоже, вы передаете исключения клиенту. WCF не любит регулярные исключения, ему нужны ошибки или FaultException в случае ошибок. После и исключение было возвращено, канал находится в неисправном состоянии и не может использоваться снова. После FaultException канал все еще может использоваться.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...