Служба WCF Net.tcp случайным образом дает сбой

Этот код немного изменен и почти взят прямо из примеров из Интернета по запуску дуплексной службы net.tcp с механизмом публикации/подписки. Какое-то время это прекрасно работает, но клиенты случайным образом ошибаются в канале, используемом для связи. Некоторые клиенты все еще хороши для общения в течение 24–48 часов до отказа. Вопрос: Кто-нибудь знает, почему сокет случайно прерывается или даже как узнать, что именно вызывает исключение в журналах ошибок?

 using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using System.Text;


    namespace WcfService1
    {

    [ServiceContract(CallbackContract = typeof(IClientCallBack))]
    interface IService
    {
        //The Alert Server Function called by the Client
        [OperationContract(IsOneWay = true)]
        void SubscribeToBeNotifiedServer(string EmpID);


        [OperationContract(IsOneWay = true)]
        void UpdatePricingServer(string ReservationID, string CustomerID);


        [OperationContract(IsOneWay = true)]
        void SendMessageToNotifyOther(string From, string To, string Message);


    }

    [ServiceContract]
    public interface IClientCallBack
        {
            [OperationContract()]
            [FaultContract(typeof(InvalidOperationException))]
            void UpdatePricingClient(string FromReservationID, string CustomerID );

            //The Alert Server Function called by the Client
            [OperationContract(IsOneWay = true)]
            void SubscribeToBeNotifiedClient();

            [OperationContract()]
            [FaultContract(typeof(InvalidOperationException))]
            void ReceiveMessage(string From, string Message);


        }


    [ServiceBehavior( ConcurrencyMode = ConcurrencyMode.Reentrant,UseSynchronizationContext =   false,  InstanceContextMode = InstanceContextMode.Single, IncludeExceptionDetailInFaults=true )]
    [CallbackBehavior(UseSynchronizationContext = false)]     
    class Service1 : IService
        {
          public Service1()
          {



          }

          public void SubscribeToBeNotifiedServer(string EmpID)
          {
              var added = OperationContext.Current.GetCallbackChannel<IClientCallBack>();

              var st = OperationContext.Current.InstanceContext.State;

              var asdf1 = OperationContext.Current.Host.State;

              if (!subscribers.Select(x => x.CallBackInformation).Contains(added))
              {
                  subscribers.Add(new ClientInfo(added, OperationContext.Current, EmpID));

                  OperationContext.Current.Channel.Faulted += new EventHandler(Channel_Faulted);

              }
          }          

          private static readonly List<ClientInfo> subscribers = new List<ClientInfo>();  

          public void UpdatePricingServer(string ReservationID, string CustomerID)
           {                  

               try
               {


                   List<ClientInfo> Remove = new List<ClientInfo>();

                   Action<ClientInfo> invoke = delegate(ClientInfo callback)
                   {

    //I wrapped this in its own thread as the entire thread gets torn down if there is an exception 
    // when you call the client. This is true even if its in a try catch the entire thread dies. 

    System.Threading.Thread mythread = new System.Threading.Thread((System.Threading.ThreadStart)delegate() {
        try
        {

            var test = (ICommunicationObject)callback.CallBackInformation;

            if (test.State == CommunicationState.Opened && callback.InstanceContext.Host.State == CommunicationState.Opened)
            {



                callback.CallBackInformation.UpdatePricingClient(ReservationID, CustomerID);


            }

            else
            {
                Remove.Add(callback);
            }

        }
        catch (FaultException<InvalidOperationException> exception)
        { }
        catch (FaultException exception)
        { }
        catch (CommunicationException exception)
        { }
    });



    mythread.Start();


    };

                   subscribers.ForEach(invoke);

                   foreach (var temp1 in Remove)
                   {
                       subscribers.Remove(temp1);
                   }





               }
               catch (Exception ex)
               {


               }
           }

          public void SendMessageToNotifyOther(string From, string To, string Message)
          {

              try
              {


                  List<ClientInfo> Remove = new List<ClientInfo>();

                  Action<ClientInfo> invoke = delegate(ClientInfo callback)
                  {

                      //I wrapped this in its own thread as the entire thread gets torn down if there is an exception 
                      // when you call the client. This is true even if its in a try catch the entire thread dies. 

                      System.Threading.Thread mythread = new System.Threading.Thread((System.Threading.ThreadStart)delegate()
                      {
                          try
                          {

                              var test = (ICommunicationObject)callback.CallBackInformation;

                              if (test.State == CommunicationState.Opened && callback.InstanceContext.Host.State == CommunicationState.Opened)
                              {


                                  if (callback.EmployeeID == To)
                                  {
                                      callback.CallBackInformation.ReceiveMessage(From, Message);
                                  }

                              }

                              else
                              {
                                  Remove.Add(callback);
                              }

                          }
                          catch (FaultException<InvalidOperationException> exception)
                          { }
                          catch (FaultException exception)
                          { }
                          catch (CommunicationException exception)
                          { }
                      });



                      mythread.Start();


                  };

                  subscribers.ForEach(invoke);

                  foreach (var temp1 in Remove)
                  {
                      subscribers.Remove(temp1);
                  }





              }
              catch (Exception ex)
              {


              }
          }



           #region IService Members
           void Channel_Faulted(object sender, EventArgs e)
           {
               ICommunicationObject myobj = (ICommunicationObject)sender;

               myobj.Abort();

               myobj.Close();

           }

           void InstanceContext_Closing(object sender, EventArgs e)
            {
                try
                {
                    subscribers.Remove(subscribers.Where(x => x.CallBackInformation == sender).FirstOrDefault());
                }
                catch { }
            }

            void Channel_Closed(object sender, EventArgs e)
            {
                try
                {
                    subscribers.Remove(subscribers.Where(x => x.CallBackInformation == sender).FirstOrDefault());
                }
                catch { }
            }

            void InstanceContext_Closed(object sender, EventArgs e)
            {
                try
                {
                    subscribers.Remove(subscribers.Where(x => x.CallBackInformation == sender).FirstOrDefault());
                }
                catch { }
            }

            void InstanceContext_Faulted(object sender, EventArgs e)
            {
                try
                {
                    subscribers.Remove(subscribers.Where(x => x.CallBackInformation == sender).FirstOrDefault());
                }
                catch { }
            }



            #endregion
        }

    public class ClientInfo
      {
          IClientCallBack client;

          OperationContext context;

          public ClientInfo(IClientCallBack clientcall, OperationContext Instance, string EmpID)
          {
              this.client = clientcall;

              this.context = Instance;

              this.EmployeeID = EmpID;
          }

          public IClientCallBack CallBackInformation
          {
              get { return client; }
              set { this.client = value; }
          }

          public OperationContext InstanceContext
          {
              get { return context; }
              set { this.context = value; }
          }

          public string EmployeeID;
      }




    }

Вот web.config сервера

 <?xml version="1.0"?>
    <configuration>
      <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <customErrors mode="Off">    
    </customErrors>
      </system.web>

      <system.serviceModel>
        <!--WcfService1.IService-->  

    <services>
      <service behaviorConfiguration="MyBehavior" name="WcfService1.Service1">
        <endpoint address="" binding="netTcpBinding"
          bindingConfiguration="portSharingBinding" name="MyServiceEndpoint"
          contract="WcfService1.IService">
          <identity>
            <!--<dns value="localhost:808" />-->
          </identity>
        </endpoint>

        <endpoint address="/mex" kind="mexEndpoint"
                  binding="mexTcpBinding" 
                  contract="IMetadataExchange" />        
        <host>
          <baseAddresses>
            <!--<add baseAddress="net.tcp://iiswatso/MnetTcp/Service1.svc" />-->
            <add baseAddress="net.tcp://localhost/WcfService/Service1.svc" />
          </baseAddresses>
        </host>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="MyBehavior" >
          <serviceTimeouts />          
          <serviceMetadata httpGetEnabled="false" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <bindings>
      <netTcpBinding>
        <binding name="portSharingBinding" portSharingEnabled="true" openTimeout="infinite" closeTimeout="infinite" receiveTimeout="infinite" sendTimeout="infinite"    >
          <reliableSession inactivityTimeout="infinite" ordered="True"    enabled="true" />
          <security mode="None"></security>          
        </binding>
      </netTcpBinding>
    </bindings>
  </system.serviceModel>
  <system.webServer>   
  </system.webServer>

  <system.diagnostics>
    <trace autoflush="true"></trace>
    <sources>
      <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
        <listeners>          
          <add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="c:\log\Server3.svclog" />
        </listeners>
      </source>
    </sources>   
  </system.diagnostics>  
</configuration>

Вот журнал трассировки для сервера:

 <E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent">
    <System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system">
 <EventID>131075</EventID>
<Type>3</Type>
<SubType Name="Error">0</SubType>
<Level>2</Level>
<TimeCreated SystemTime="2012-05-30T18:11:10.9002453Z" />
<Source Name="System.ServiceModel" />
<Correlation ActivityID="{00000000-0000-0000-0000-000000000000}" />
<Execution ProcessName="Meridian Reservation System.vshost" ProcessID="10676" ThreadID="21" />
<Channel />
<Computer>JIMMY-PC</Computer>
</System>
<ApplicationData>
<TraceData>
<DataItem>
<TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error">
<TraceIdentifier>http://msdn.microsoft.com/en-US/library/System.ServiceModel.Diagnostics.ThrowingException.aspx</TraceIdentifier>
<Description>Throwing an exception.</Description>
<AppDomain>Meridian Reservation System.vshost.exe</AppDomain>
<Exception>
<ExceptionType>System.ServiceModel.CommunicationException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '10675199.02:48:05.4775807'.</Message>
<StackTrace>
at System.ServiceModel.Channels.SocketConnection.BeginReadCore(Int32 offset, Int32 size, TimeSpan timeout, WaitCallback callback, Object state)
at System.ServiceModel.Channels.SocketConnection.BeginRead(Int32 offset, Int32 size, TimeSpan timeout, WaitCallback callback, Object state)
at System.ServiceModel.Channels.DelegatingConnection.BeginRead(Int32 offset, Int32 size, TimeSpan timeout, WaitCallback callback, Object state)
at System.ServiceModel.Channels.SessionConnectionReader.BeginReceive(TimeSpan timeout, WaitCallback callback, Object state)
at System.ServiceModel.Channels.SynchronizedMessageSource.ReceiveAsyncResult.PerformOperation(TimeSpan timeout)
at System.ServiceModel.Channels.SynchronizedMessageSource.SynchronizedAsyncResult`1..ctor(SynchronizedMessageSource syncSource, TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.SynchronizedMessageSource.ReceiveAsyncResult..ctor(SynchronizedMessageSource syncSource, TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.SynchronizedMessageSource.BeginReceive(TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.FramingDuplexSessionChannel.BeginReceive(TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.FramingDuplexSessionChannel.TryReceiveAsyncResult..ctor(FramingDuplexSessionChannel channel, TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.FramingDuplexSessionChannel.BeginTryReceive(TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.ClientReliableChannelBinder`1.DuplexClientReliableChannelBinder`1.OnBeginTryReceive(TDuplexChannel channel, TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.ReliableChannelBinder`1.TryReceiveAsyncResult.BeginInput(ReliableChannelBinder`1 binder, TChannel channel, TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.ReliableChannelBinder`1.InputAsyncResult`1.CompleteTryGetChannel(IAsyncResult result, Boolean&amp; complete)
at System.ServiceModel.Channels.ReliableChannelBinder`1.InputAsyncResult`1.Start()
at System.ServiceModel.Channels.ReliableChannelBinder`1.TryReceiveAsyncResult..ctor(ReliableChannelBinder`1 binder, TimeSpan timeout, MaskingMode maskingMode, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.ReliableChannelBinder`1.BeginTryReceive(TimeSpan timeout, MaskingMode maskingMode, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.ReliableChannelBinder`1.BeginTryReceive(TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.ReliableDuplexSessionChannel.StartReceiving(Boolean canBlock)
at System.ServiceModel.Channels.ReliableDuplexSessionChannel.HandleReceiveComplete(IAsyncResult result)
at System.ServiceModel.Channels.ReliableDuplexSessionChannel.OnReceiveCompletedStatic(IAsyncResult result)
at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously, Exception exception)
at System.ServiceModel.Channels.ReliableChannelBinder`1.InputAsyncResult`1.OnInputComplete(IAsyncResult result)
at System.ServiceModel.Channels.ReliableChannelBinder`1.InputAsyncResult`1.OnInputCompleteStatic(IAsyncResult result)
at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously, Exception exception)
at System.ServiceModel.Channels.FramingDuplexSessionChannel.TryReceiveAsyncResult.OnReceive(IAsyncResult result)
at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously, Exception exception)
at System.ServiceModel.Channels.SynchronizedMessageSource.SynchronizedAsyncResult`1.CompleteWithUnlock(Boolean synchronous, Exception exception)
at System.ServiceModel.Channels.SynchronizedMessageSource.ReceiveAsyncResult.OnReceiveComplete(Object state)
at System.ServiceModel.Channels.SessionConnectionReader.OnAsyncReadComplete(Object state)
at System.ServiceModel.Channels.SocketConnection.FinishRead()
at System.ServiceModel.Channels.SocketConnection.AsyncReadCallback(Boolean haveResult, Int32 error, Int32 bytesRead)
at System.ServiceModel.Channels.OverlappedContext.CompleteCallback(UInt32 error, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
</StackTrace>
<ExceptionString>System.ServiceModel.CommunicationException: The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '10675199.02:48:05.4775807'. ---&gt; System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
   --- End of inner exception stack trace ---</ExceptionString>
<InnerException>
<ExceptionType>System.Net.Sockets.SocketException, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>An existing connection was forcibly closed by the remote host</Message>
<StackTrace>
at System.ServiceModel.Channels.SocketConnection.BeginReadCore(Int32 offset, Int32 size, TimeSpan timeout, WaitCallback callback, Object state)
at System.ServiceModel.Channels.SocketConnection.BeginRead(Int32 offset, Int32 size, TimeSpan timeout, WaitCallback callback, Object state)
at System.ServiceModel.Channels.DelegatingConnection.BeginRead(Int32 offset, Int32 size, TimeSpan timeout, WaitCallback callback, Object state)
at System.ServiceModel.Channels.SessionConnectionReader.BeginReceive(TimeSpan timeout, WaitCallback callback, Object state)
at System.ServiceModel.Channels.SynchronizedMessageSource.ReceiveAsyncResult.PerformOperation(TimeSpan timeout)
at System.ServiceModel.Channels.SynchronizedMessageSource.SynchronizedAsyncResult`1..ctor(SynchronizedMessageSource syncSource, TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.SynchronizedMessageSource.ReceiveAsyncResult..ctor(SynchronizedMessageSource syncSource, TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.SynchronizedMessageSource.BeginReceive(TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.FramingDuplexSessionChannel.BeginReceive(TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.FramingDuplexSessionChannel.TryReceiveAsyncResult..ctor(FramingDuplexSessionChannel channel, TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.FramingDuplexSessionChannel.BeginTryReceive(TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.ClientReliableChannelBinder`1.DuplexClientReliableChannelBinder`1.OnBeginTryReceive(TDuplexChannel channel, TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.ReliableChannelBinder`1.TryReceiveAsyncResult.BeginInput(ReliableChannelBinder`1 binder, TChannel channel, TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.ReliableChannelBinder`1.InputAsyncResult`1.CompleteTryGetChannel(IAsyncResult result, Boolean&amp; complete)
at System.ServiceModel.Channels.ReliableChannelBinder`1.InputAsyncResult`1.Start()
at System.ServiceModel.Channels.ReliableChannelBinder`1.TryReceiveAsyncResult..ctor(ReliableChannelBinder`1 binder, TimeSpan timeout, MaskingMode maskingMode, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.ReliableChannelBinder`1.BeginTryReceive(TimeSpan timeout, MaskingMode maskingMode, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.ReliableChannelBinder`1.BeginTryReceive(TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.ReliableDuplexSessionChannel.StartReceiving(Boolean canBlock)
at System.ServiceModel.Channels.ReliableDuplexSessionChannel.HandleReceiveComplete(IAsyncResult result)
at System.ServiceModel.Channels.ReliableDuplexSessionChannel.OnReceiveCompletedStatic(IAsyncResult result)
at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously, Exception exception)
at System.ServiceModel.Channels.ReliableChannelBinder`1.InputAsyncResult`1.OnInputComplete(IAsyncResult result)
at System.ServiceModel.Channels.ReliableChannelBinder`1.InputAsyncResult`1.OnInputCompleteStatic(IAsyncResult result)
at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously, Exception exception)
at System.ServiceModel.Channels.FramingDuplexSessionChannel.TryReceiveAsyncResult.OnReceive(IAsyncResult result)
at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously, Exception exception)
at System.ServiceModel.Channels.SynchronizedMessageSource.SynchronizedAsyncResult`1.CompleteWithUnlock(Boolean synchronous, Exception exception)
at System.ServiceModel.Channels.SynchronizedMessageSource.ReceiveAsyncResult.OnReceiveComplete(Object state)
at System.ServiceModel.Channels.SessionConnectionReader.OnAsyncReadComplete(Object state)
at System.ServiceModel.Channels.SocketConnection.FinishRead()
at System.ServiceModel.Channels.SocketConnection.AsyncReadCallback(Boolean haveResult, Int32 error, Int32 bytesRead)
at System.ServiceModel.Channels.OverlappedContext.CompleteCallback(UInt32 error, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
</StackTrace>
<ExceptionString>System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host</ExceptionString>
<NativeErrorCode>2746</NativeErrorCode>
</InnerException>
</Exception>
</TraceRecord>
</DataItem>
</TraceData>
</ApplicationData>
</E2ETraceEvent>

Трассировка для клиента:

     <E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent">
<System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system">
<EventID>131075</EventID>
<Type>3</Type>
<SubType Name="Error">0</SubType>
<Level>2</Level>
<TimeCreated SystemTime="2012-05-30T18:11:02.2488000Z" />
<Source Name="System.ServiceModel" />
<Correlation ActivityID="{54830e63-b315-4f74-9455-d9ba50c655c0}" />
<Execution ProcessName="w3wp" ProcessID="2716" ThreadID="6" />
<Channel />
<Computer>IISWATSO</Computer>
</System>
<ApplicationData>
<TraceData>
<DataItem>
<TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error">
<TraceIdentifier>http://msdn.microsoft.com/en-US/library/System.ServiceModel.Diagnostics.ThrowingException.aspx</TraceIdentifier>
<Description>Throwing an exception.</Description>
<AppDomain>/LM/W3SVC/3/ROOT/MNetTcp-1-129828750305652000</AppDomain>
<Exception>
<ExceptionType>System.ServiceModel.CommunicationException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '10675199.02:48:05.4775807'.</Message>
<StackTrace>
at System.ServiceModel.Channels.SocketConnection.EndRead()
at System.ServiceModel.Channels.TracingConnection.EndRead()
at System.ServiceModel.Channels.SessionConnectionReader.OnAsyncReadComplete(Object state)
at System.ServiceModel.Channels.TracingConnection.TracingConnectionState.ExecuteCallback()
at System.ServiceModel.Channels.SocketConnection.AsyncReadCallback(Boolean haveResult, Int32 error, Int32 bytesRead)
at System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
</StackTrace>
<ExceptionString>System.ServiceModel.CommunicationException: The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '10675199.02:48:05.4775807'. ---&gt; System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
   --- End of inner exception stack trace ---</ExceptionString>
<InnerException>
<ExceptionType>System.Net.Sockets.SocketException, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>An existing connection was forcibly closed by the remote host</Message>
<StackTrace>
at System.ServiceModel.Channels.SocketConnection.EndRead()
at System.ServiceModel.Channels.TracingConnection.EndRead()
at System.ServiceModel.Channels.SessionConnectionReader.OnAsyncReadComplete(Object state)
at System.ServiceModel.Channels.TracingConnection.TracingConnectionState.ExecuteCallback()
at System.ServiceModel.Channels.SocketConnection.AsyncReadCallback(Boolean haveResult, Int32 error, Int32 bytesRead)
at System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, Nativ

person Watson    schedule 05.06.2012    source источник
comment
Как это слишком широко? Сам код взят из образца кода от Microsoft, очень и очень слегка измененного. Это самая упрощенная версия запуска дуплексной службы net.tcp. Я перечислил здесь все, что знаю о проблеме - не вопрос? Мой вопрос довольно реален и довольно ясен - почему, черт возьми, этот простой сервис случайно дает сбой.   -  person Watson    schedule 05.06.2012
comment
Когда решу эту проблему, отпишусь здесь.   -  person Watson    schedule 06.06.2012
comment
Кроме того, я хотел добавить, что этот пост занял у меня больше времени, чем время, которое потребовалось какому-то модератору, чтобы закрыть его. Я решу эту проблему и опубликую здесь, чтобы другие могли видеть. Но я больше не буду пользоваться этим сайтом. Если вопрос не подходит, пусть сообщество сообщит мне, а не какому-то диктатору. Удачи и спасибо за рыбу.   -  person Watson    schedule 06.06.2012
comment
У меня была точно такая же проблема, хотя она возникла в течение гораздо более длительного периода времени (т.е. обслуживание длилось дни или недели, а не 24-48 часов). Вы когда-нибудь добирались до сути этого? Было бы очень полезно, если бы у вас были какие-либо результаты, которыми вы могли бы поделиться.   -  person Lewray    schedule 03.07.2012
comment
Я только что наткнулся на это, которое я могу воспроизвести и, кажется, постоянно создает одно и то же исключение. Я все еще ищу обходные пути, хотя...   -  person Lewray    schedule 03.07.2012
comment
Я хотел бы добраться до сути, но я был очень занят. Я отпишусь здесь, когда найду что-нибудь.   -  person Watson    schedule 07.08.2012
comment
Lewray дайте мне знать, если вы тестируете свое приложение в Visual Studio 2012 с платформой .net 4.5. Из того, что я прочитал в вашей ссылке, что может решить проблему? Спасибо за помощь Льюрэю.   -  person Watson    schedule 05.09.2012
comment
Итак, еще две вещи, на которые вы должны обратить внимание при создании дуплексной службы wcf, которую вы хотите поддерживать на неопределенный срок. Какой бы пул приложений вы не использовали для службы nettcp, убедитесь, что в этом пуле приложений отключена переработка. Во-вторых, убедитесь, что sendtimeout не установлен на бесконечность. В противном случае сервер никогда не откажется от отправки клиенту, даже если этот клиент ушел.   -  person Watson    schedule 22.10.2012


Ответы (1)


У вас есть как минимум 9 пустых блоков catch, это означает, что вы проглатываете ошибки и не можете увидеть, какая ошибка произошла.

Первое, что вы должны сделать, это поместить код регистрации в каждый блок catch для регистрации ошибки.

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

person Shiraz Bhaiji    schedule 05.06.2012
comment
Ваш комментарий не очень ясен. Я оставляю канал открытым? Да, верно, мы формируем список людей для трансляции. Каналы, оставленные открытыми, не должны переходить в неисправное состояние. Тайм-аут установлен на бесконечность. Я могу удалить перехваты попыток — я использовал их, чтобы поддерживать работу службы в режиме отладки и видеть, когда они попадают в эти категории. - person Watson; 05.06.2012
comment
Проблема в том, что ваш дизайн неправильный. Вы не можете удерживать соединение открытым идентифицированным образом. - person Shiraz Bhaiji; 06.06.2012
comment
Что мешает вам удерживать соединение открытым, пока нет прерывания? Нет причин отключать службу, если соединение не прерывается. С удаленным взаимодействием .net я создал сервисы, которые не работали в течение длительного периода времени — я хотел использовать WCF, но это не выглядело многообещающе. - person Watson; 06.06.2012
comment
Кстати, когда вы говорите, что мой дизайн неправильный - я не проектировал этот пример. Я нашел этот пример в нескольких местах — одно место, которое я помню, было сайтом, размещенным Microsoft. Код, который я добавил, не актуален. - person Watson; 06.06.2012
comment
Шираз Бхаиджи, между прочим, спасибо за конструктивность и за то, что действительно добавили что-то к этому разговору, вы потрясающие. - person Watson; 06.06.2012
comment
stackoverflow.com/questions/8672061/ - person Watson; 07.06.2012