0

此代码稍作修改,几乎直接取自 Internet 上的示例,该示例使用发布/订阅机制运行 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
4

1 回答 1

3

您至少有 9 个空的 catch 块,这意味着您正在吞下错误并且无法看到发生了什么错误。

您应该做的第一件事是将日志记录代码放在每个 catch 块中以记录错误。

从您发布的代码看来,您正在打开通道,您没有打开通道,使用它并尽快关闭它。最终,保持打开状态的通道将进入故障状态。

于 2012-06-05T17:43:24.503 回答