none
Зависает конечная точка WCF при этом другие конечные точки сервиса продолжают работать.

    Вопрос

  • Периодически зависает одна из конечных точек сервиса, при этом все остальные конечные точки сервиса продолжают работать,

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

    //аттрибуты конечной точки на которой возникает зависание:
        [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
        [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple, AddressFilterMode = AddressFilterMode.Any)]
     
        public class TechPlan : ITechPlan
        {
    }

    24 октября 2018 г. 2:19

Все ответы

  • <?xml version="1.0"?>
    <configuration>
      <configSections>
        <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
        </sectionGroup>
        <section name="log4net"
           type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
      </configSections>
      <appSettings>
        <add key="ConfigFileName" value="Service.config" />
      </appSettings>
      <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
        <session-factory>
          <property name="connection.driver_class">NHibernate.Driver.NpgsqlDriver</property>
    ConnectionString      <property name="connection.connection_string">

        </property>
          <property name="show_sql">false</property>
          <property name="dialect">NHibernate.Dialect.PostgreSQLDialect</property>
          <property name="hbm2ddl.keywords">auto-quote</property>
          <mapping assembly="BusinessModel" />
        </session-factory>
      </hibernate-configuration>

      <system.diagnostics>
        <sources>
          <source name="System.ServiceModel" switchValue="Error"
                  propagateActivity="false">
            <listeners>
              <add type="System.Diagnostics.DefaultTraceListener" name="Default">
                <filter type="" />
              </add>
              <add name="ServiceModelTraceListener">
                <filter type="" />
              </add>
            </listeners>
          </source>
        </sources>
        <sharedListeners>
          <add initializeData="С:\Path\test.svclog"
               type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
               name="ServiceModelTraceListener"
               traceOutputOptions="DateTime, Timestamp, Callstack">
            <filter type="" />
          </add>
        </sharedListeners>
        <trace autoflush="true" />
      </system.diagnostics>
      <system.serviceModel>
        <bindings>
          <netTcpBinding>
            <binding name="binding" maxConnections="10000"  listenBacklog="10000"  portSharingEnabled="true" openTimeout="00:01:00" sendTimeout="03:00:00" receiveTimeout="03:00:00" closeTimeout="00:01:00" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
              <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
              <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="true" />

              <security mode="Transport">
                <transport protectionLevel="EncryptAndSign"   clientCredentialType="None"></transport>
              </security>
            </binding>
    <!--       
        <binding name="NetTcpBindingEndpointclient" closeTimeout="01:00:00"
             openTimeout="01:00:00" receiveTimeout="00:10:00" sendTimeout="01:00:00"
             transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
             hostNameComparisonMode="StrongWildcard" listenBacklog="10"
             maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxConnections="10"
             maxReceivedMessageSize="2147483647">
            <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647"
                maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
            <reliableSession ordered="true" inactivityTimeout="00:10:00"
                enabled="false" />
            <security mode="None">
            </security>
          </binding>
           <binding name="bindinginternal" maxConnections="1000"  listenBacklog="1000"  portSharingEnabled="true" openTimeout="00:01:00" sendTimeout="03:00:00" receiveTimeout="03:00:00" closeTimeout="00:01:00" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
              <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
              <security mode="None">
              </security>
            </binding>
    -->       
          </netTcpBinding>
        </bindings>
        <extensions>
          <behaviorExtensions>
             <add name="Extension" type="WebServiceCadTech.XMLBehaviorExtensionElement,WebServiceCadTech, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
          </behaviorExtensions>
        </extensions>
        <!-- This section is optional with the new configuration model
               introduced in .NET Framework 4. -->
        <services>

          <service behaviorConfiguration="CommonServiceBehavior" name="WebServiceCadTech.TechPlan">
            <endpoint address="" binding="netTcpBinding" bindingConfiguration="binding" name="binding" contract="Assembly.ITechPlan">
            </endpoint>
            <endpoint
                               address="mex"
                               binding="netTcpBinding"
                               bindingConfiguration="binding"
                               name="NetTcpMetadataPoint"
                               contract="IMetadataExchange" />
            <host>
              <baseAddresses>
                <add baseAddress="net.tcp://address/TechPlan" />
              </baseAddresses>
            </host>
          </service>
          <service behaviorConfiguration="CommonServiceBehavior" name="WebServiceCadTech.Autorize">
            <endpoint address="" binding="netTcpBinding" bindingConfiguration="binding" name="NetTcpBindingEndpoint1" contract="assembly.IAutentificateService">

            </endpoint>
            <endpoint
                               address="mex"
                               binding="netTcpBinding"
                               bindingConfiguration="binding"
                               name="NetTcpMetadataPoint"
                               contract="IMetadataExchange" />

            <host>
              <baseAddresses>
                <add baseAddress="net.tcp://address/Autorize" />
              </baseAddresses>
            </host>
          </service>
          <service behaviorConfiguration="CommonServiceBehavior" name="WebServiceCadTech.MezhPlanService">
            <endpoint address="" binding="netTcpBinding" bindingConfiguration="binding" name="binding" contract="assembly.IMezhPlanService">
            </endpoint>
            <endpoint
                               address="mex"
                               binding="netTcpBinding"
                               bindingConfiguration="binding"
                               name="NetTcpMetadataPoint"
                               contract="IMetadataExchange" />
            <host>
              <baseAddresses>
                <add baseAddress="net.tcp://address/MezhPlanService" />
              </baseAddresses>
            </host>
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
             <behavior name="CommonServiceBehavior">
              <serviceCredentials>
                <serviceCertificate findValue="server.ru" storeName="My" storeLocation="LocalMachine"
                                    x509FindType="FindBySubjectName" />


              </serviceCredentials>

              <serviceMetadata httpsGetEnabled="false" httpGetEnabled="false" />
              <dataContractSerializer maxItemsInObjectGraph="22240310" />
              <serviceDebug includeExceptionDetailInFaults="true" />
              <serviceThrottling maxConcurrentCalls="1024" maxConcurrentSessions="6400" maxConcurrentInstances="7424" />
            </behavior>
          </serviceBehaviors>
          <endpointBehaviors>
            <behavior name="behavior">
          <Extension/>
    <!--
              <clientCredentials>
                <clientCertificate findValue="server.ru" storeName="My" storeLocation="LocalMachine"
                                    x509FindType="FindByIssuerName"/>
              </clientCredentials>
    -->
            </behavior>
          </endpointBehaviors>
            </behaviors>
      </system.serviceModel>
      <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
      </startup>
      <system.web>
        <membership defaultProvider="ClientAuthenticationMembershipProvider">
          <providers>
            <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
          </providers>
        </membership>
        <roleManager defaultProvider="ClientRoleProvider" enabled="true">
          <providers>
            <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
          </providers>
        </roleManager>
      </system.web>
    </configuration>

                                    
    • Изменено UserAzure55 24 октября 2018 г. 4:57
    24 октября 2018 г. 2:31
  • Вот ссылка  на данные счетчиков производительности: https://drive.google.com/open?id=1083MKbED3JQVQ-Fy-iio1zR8jJmZEluG
    24 октября 2018 г. 2:32
  • Поставил ReceiveTimeout и SendTimeOut в 10 минут

    Заметил одну интересную штуку, на праздниках, естественно нагрузка на сервис падает,и по логам операций зафиксирован провал в работе сервиса допустим с 9:44 часов утра до 11, но в wcf логе ошибок присутствует странная запись

    в 10:04 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="2018-11-04T03:04:27.1149553Z" />
    <Source Name="System.ServiceModel" />
    <Correlation ActivityID="{00000000-0000-0000-0000-000000000000}" />
    <Execution ProcessName="MyService" ProcessID="2224" ThreadID="31" />
    <Channel />
    <Computer>еуые</Computer>
    </System>
    <ApplicationData>
    <TraceData>
    <DataItem>
    <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error">
    <TraceIdentifier>http://msdn.microsoft.com/ru-RU/library/System.ServiceModel.Diagnostics.ThrowingException.aspx</TraceIdentifier>
    <Description>Throwing an exception.</Description>
    <AppDomain>еуые</AppDomain>
    <Source>System.ServiceModel.Channels.ServerReliableDuplexSessionChannel/29206075</Source>
    <Exception>
    <ExceptionType>System.ServiceModel.CommunicationObjectFaultedException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
    <Message>The communication object, System.ServiceModel.Channels.ServerReliableDuplexSessionChannel, cannot be used for communication because it is in the Faulted state.</Message>
    <StackTrace>
    at System.ServiceModel.Channels.CommunicationObject.Close(TimeSpan timeout)
    at System.ServiceModel.Channels.CommunicationObject.Close()
    at System.ServiceModel.Dispatcher.ErrorHandlingReceiver.Close()
    at System.ServiceModel.Dispatcher.ChannelHandler.HandleReceiveComplete(RequestContext context)
    at System.ServiceModel.Dispatcher.ChannelHandler.EndTryReceive(IAsyncResult result, RequestContext&amp; requestContext)
    at System.ServiceModel.Dispatcher.ChannelHandler.AsyncMessagePump(IAsyncResult result)
    at System.ServiceModel.Dispatcher.ChannelHandler.OnAsyncReceiveComplete(IAsyncResult result)
    at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
    at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
    at System.Runtime.InputQueue`1.AsyncQueueReader.Set(Item item)
    at System.Runtime.InputQueue`1.Shutdown(Func`1 pendingExceptionGenerator)
    at System.ServiceModel.Channels.InputQueueChannel`1.OnFaulted()
    at System.ServiceModel.Channels.ReliableDuplexSessionChannel.OnFaulted()
    at System.ServiceModel.Channels.ServerReliableDuplexSessionChannel.OnFaulted()
    at System.ServiceModel.Channels.CommunicationObject.Fault()
    at System.ServiceModel.Channels.CommunicationObject.Fault(Exception exception)
    at System.ServiceModel.Channels.ChannelReliableSession.OnLocalFault(Exception e, Message faultMessage, RequestContext context)
    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.StartOnNonUserThread()
    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.TransportDuplexSessionChannel.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.ReceiveAsyncResult.OnReceiveComplete(Object state)
    at System.ServiceModel.Channels.SessionConnectionReader.OnAsyncReadComplete(Object state)
    at System.ServiceModel.Channels.StreamConnection.OnRead(IAsyncResult result)
    at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
    at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
    at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
    at System.Net.Security._SslStream.StartFrameBody(Int32 readBytes, Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
    at System.Net.Security._SslStream.ReadHeaderCallback(AsyncProtocolRequest asyncRequest)
    at System.Net.AsyncProtocolRequest.CompleteRequest(Int32 result)
    at System.Net.FixedSizeReader.CheckCompletionBeforeNextRead(Int32 bytes)
    at System.Net.FixedSizeReader.ReadCallback(IAsyncResult transportResult)
    at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
    at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously, Exception exception)
    at System.ServiceModel.Channels.ConnectionStream.IOAsyncResult.OnAsyncIOComplete(Object state)
    at System.ServiceModel.Channels.SocketConnection.FinishRead()
    at System.ServiceModel.Channels.SocketConnection.OnReceiveAsync(Object sender, SocketAsyncEventArgs eventArgs)
    at System.ServiceModel.Channels.SocketConnection.OnReceiveAsyncCompleted(Object sender, SocketAsyncEventArgs e)
    at System.Net.Sockets.SocketAsyncEventArgs.OnCompleted(SocketAsyncEventArgs e)
    at System.Net.Sockets.SocketAsyncEventArgs.FinishOperationSuccess(SocketError socketError, Int32 bytesTransferred, SocketFlags flags)
    at System.Net.Sockets.SocketAsyncEventArgs.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
    at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
    </StackTrace>
    <ExceptionString>System.ServiceModel.CommunicationObjectFaultedException: The communication object, System.ServiceModel.Channels.ServerReliableDuplexSessionChannel, cannot be used for communication because it is in the Faulted state.</ExceptionString>
    </Exception>
    </TraceRecord>
    </DataItem>
    </TraceData>
    <System.Diagnostics xmlns="http://schemas.microsoft.com/2004/08/System.Diagnostics">
    <Timestamp>22949550695103</Timestamp>
    <Callstack>
    at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
    at System.Environment.get_StackTrace()
    at System.Diagnostics.TraceEventCache.get_Callstack()
    at System.Diagnostics.XmlWriterTraceListener.WriteFooter(TraceEventCache eventCache)
    at System.Diagnostics.XmlWriterTraceListener.TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, Int32 id, Object data)
    at System.Diagnostics.TraceSource.TraceData(TraceEventType eventType, Int32 id, Object data)
    at System.ServiceModel.Diagnostics.LegacyDiagnosticTrace.TraceEvent(TraceEventType type, Int32 code, String msdnTraceCode, String description, TraceRecord trace, Exception exception, Object source)
    at System.ServiceModel.Diagnostics.LegacyDiagnosticTrace.TraceEvent(TraceEventType type, Int32 code, String msdnTraceCode, String description, TraceRecord trace, Exception exception, Guid activityId, Object source)
    at System.ServiceModel.Diagnostics.TraceUtility.ThrowHelperError(Exception exception, Guid activityId, Object source)
    at System.ServiceModel.Channels.CommunicationObject.Close(TimeSpan timeout)
    at System.ServiceModel.Channels.CommunicationObject.Close()
    at System.ServiceModel.Dispatcher.ErrorHandlingReceiver.Close()
    at System.ServiceModel.Dispatcher.ChannelHandler.HandleReceiveComplete(RequestContext context)
    at System.ServiceModel.Dispatcher.ChannelHandler.EndTryReceive(IAsyncResult result, RequestContext& requestContext)
    at System.ServiceModel.Dispatcher.ChannelHandler.AsyncMessagePump(IAsyncResult result)
    at System.ServiceModel.Dispatcher.ChannelHandler.OnAsyncReceiveComplete(IAsyncResult result)
    at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
    at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
    at System.Runtime.InputQueue`1.AsyncQueueReader.Set(Item item)
    at System.Runtime.InputQueue`1.Shutdown(Func`1 pendingExceptionGenerator)
    at System.ServiceModel.Channels.InputQueueChannel`1.OnFaulted()
    at System.ServiceModel.Channels.ReliableDuplexSessionChannel.OnFaulted()
    at System.ServiceModel.Channels.ServerReliableDuplexSessionChannel.OnFaulted()
    at System.ServiceModel.Channels.CommunicationObject.Fault()
    at System.ServiceModel.Channels.CommunicationObject.Fault(Exception exception)
    at System.ServiceModel.Channels.ChannelReliableSession.OnLocalFault(Exception e, Message faultMessage, RequestContext context)
    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.StartOnNonUserThread()
    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.TransportDuplexSessionChannel.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.ReceiveAsyncResult.OnReceiveComplete(Object state)
    at System.ServiceModel.Channels.SessionConnectionReader.OnAsyncReadComplete(Object state)
    at System.ServiceModel.Channels.StreamConnection.OnRead(IAsyncResult result)
    at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
    at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
    at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
    at System.Net.Security._SslStream.StartFrameBody(Int32 readBytes, Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
    at System.Net.Security._SslStream.ReadHeaderCallback(AsyncProtocolRequest asyncRequest)
    at System.Net.AsyncProtocolRequest.CompleteRequest(Int32 result)
    at System.Net.FixedSizeReader.CheckCompletionBeforeNextRead(Int32 bytes)
    at System.Net.FixedSizeReader.ReadCallback(IAsyncResult transportResult)
    at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
    at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously, Exception exception)
    at System.ServiceModel.Channels.ConnectionStream.IOAsyncResult.OnAsyncIOComplete(Object state)
    at System.ServiceModel.Channels.SocketConnection.FinishRead()
    at System.ServiceModel.Channels.SocketConnection.OnReceiveAsync(Object sender, SocketAsyncEventArgs eventArgs)
    at System.ServiceModel.Channels.SocketConnection.OnReceiveAsyncCompleted(Object sender, SocketAsyncEventArgs e)
    at System.Net.Sockets.SocketAsyncEventArgs.OnCompleted(SocketAsyncEventArgs e)
    at System.Net.Sockets.SocketAsyncEventArgs.FinishOperationSuccess(SocketError socketError, Int32 bytesTransferred, SocketFlags flags)
    at System.Net.Sockets.SocketAsyncEventArgs.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
    at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
    </Callstack>
    </System.Diagnostics>
    </ApplicationData>
    Откуда она взялась если на тот момент уже 20 минут операций не было. и ReceiveTimeout и SendTimeOut в 10 минут. Хочется услышать мнение специалистов



    • Изменено UserAzure55 6 ноября 2018 г. 3:53
    6 ноября 2018 г. 3:10
  • Как вариант, исчерпание ThreadPool. Попробуйте вместе с протоколированием запуска метода также протоколировать количество доступных потоков в ThreadPool (https://docs.microsoft.com/ru-ru/dotnet/api/system.threading.threadpool.getavailablethreads?view=netframework-4.7.2)

    6 ноября 2018 г. 9:18
  • У меня все конечные точки  работают в рамках одной виндовой службы, как такое может быть что для одной конечной точки  пул исчерпывается, а для другой нет?
    7 ноября 2018 г. 3:56
  • Не знаю. Исчерпание ThreadPool часто вызывает зависания или взаимоблокировки под нагрузкой при неправильном использовании TPL и асинхронности.  А чем отличается проблемная конечная точка от других?
    7 ноября 2018 г. 8:00
  • Сервис в настоящее время разделен на две конечные точки конечная точка аутентификации и конечная точка основного функционала системы, по мере развития предвидится увеличение количества конечных точек. Разделение на конечные точки основано на логическом разделении по функционалу. На зависающую конечную точку приходится основная нагрузка.
    7 ноября 2018 г. 8:35
  •  У вас по данным счетчиков производительности значение Faulted Calls постоянно растет. Такое поведение с самого начала работы сервиса идет, или только после начала зависаний? Вы исключения в WCF-методах как-то обрабатываете, преобразуете в Fault-сообщения, или просто позволяете методу упасть?
    • Изменено VadimTagil 7 ноября 2018 г. 11:53
    7 ноября 2018 г. 11:51
  • Преобразую в FaultException, основная часть ошибок не ошибки методов,  а однотипная ошибка "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"'00:00:59.9840000'."
    8 ноября 2018 г. 2:07
  • Ну тогда печаль, по тем данным, которые вы предоставили, не вижу что может вызвать такую проблему. По счетчикам производительности, нагрузка хоть и значительна, но не настолько, чтобы упираться в ограничения, соответствующие конфигурации, даже если каждый клиент забывал бы закрыть соединение. Либо вы в коде что-то такое делаете, что не выдерживает нагрузки, либо проблема на стороне ОС/драйверов/железа.
    8 ноября 2018 г. 4:47
  • Для поиска ошибки был написан следующий код, производящий логирование операций, так вот  перед началом каждой операции в базу записывается запись с определенным guid, а после окончания запись с тем же guid. Так вот несмотря на то сервис зависает, для каждой записи находится пара
      
     public class MyServiceHostFactory : ServiceHostFactory
        {
            protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
            {
                var serviceHost = new MyServiceHost(serviceType, baseAddresses);
                //ConfigureUnity(serviceHost.Container);
                //ConfigureAutoMapper();
                return serviceHost;
            }
            public static ConcurrentBag<CTData> logs = new ConcurrentBag<CTData>();
    
        }
        public class MyServiceHost : ServiceHost
        {
            public UnityContainer Container { get; set; }
    
            public MyServiceHost()
            {
                Container = new UnityContainer();
            }
    
            public MyServiceHost(Type serviceType, params Uri[] baseAddresses) : base(serviceType, baseAddresses)
            {
                Container = new UnityContainer();
            }
    
            protected override void OnOpening()
            {
                base.OnOpening();
    
                if (this.Description.Behaviors.Find<MyServiceBehavior>() == null)
                {
                    this.Description.Behaviors.Add(new MyServiceBehavior(Container));
                }
            }
        }
        public class MyServiceBehavior : IServiceBehavior
        {
            public UnityInstanceProvider InstanceProvider { get; set; }
    
            public MyServiceBehavior()
            {
                InstanceProvider = new UnityInstanceProvider();
                ServiceDescription desctiption = new ServiceDescription();
    
            }
    
            public MyServiceBehavior(UnityContainer unity)
            {
                InstanceProvider = new UnityInstanceProvider { Container = unity };
            }
    
            public void AddBindingParameters(ServiceDescription serviceDescription,
                            ServiceHostBase serviceHostBase,
                            Collection<ServiceEndpoint> endpoints,
                            BindingParameterCollection bindingParameters)
            {
            }
    
            public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
            {
                InstanceProvider.ServiceType = serviceDescription.ServiceType;
                foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers)
                {
                    var cd = cdb as ChannelDispatcher;
                    if (cd != null)
                    {
                        foreach (EndpointDispatcher ed in cd.Endpoints)
                        {
                            ed.DispatchRuntime.InstanceProvider = InstanceProvider;
                        }
                    }
                }
    
                //  var log = InstanceProvider.Container.Resolve<ILog>();
                IOperationBehavior behavior = new LoggingOperationBehavior();
                foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints)
                {
                    foreach (OperationDescription operation in endpoint.Contract.Operations)
                    {
                        if (!operation.Behaviors.Any(d => d is LoggingOperationBehavior))
                        {
                            operation.Behaviors.Add(behavior);
                        }
                    }
                }
            }
    
            public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
            {
            }
        }
        public class LoggingOperationBehavior : IOperationBehavior
        {
            // private readonly ILog _myLog;
    
            public LoggingOperationBehavior()
            {
                //  _myLog = myLog;
            }
    
            public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
            {
                dispatchOperation.Invoker = new LoggingOperationInvoker(dispatchOperation.Invoker, dispatchOperation);
            }
    
            public void Validate(OperationDescription operationDescription)
            {
            }
    
            public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
            {
            }
    
            public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
            {
            }
        }
        public class UnityInstanceProvider : IInstanceProvider
        {
            public IUnityContainer Container { set; get; }
            public Type ServiceType { set; get; }
    
    
            public UnityInstanceProvider()
                : this(null)
            {
            }
    
            public UnityInstanceProvider(Type type)
            {
                ServiceType = type;
                Container = new UnityContainer();
            }
    
            public object GetInstance(InstanceContext instanceContext, Message message)
            {
                return Container.Resolve(ServiceType);
            }
    
            public object GetInstance(System.ServiceModel.InstanceContext instanceContext)
            {
                return GetInstance(instanceContext, null);
            }
    
            public void ReleaseInstance(InstanceContext instanceContext, object instance)
            {
    
                var myInstance = instance as IDisposable;
    
                if (myInstance != null)
                {
                    myInstance.Dispose();
                }
            }
        }
        public class LoggingOperationInvoker : IOperationInvoker
        {
            private readonly IOperationInvoker _baseInvoker;
            private readonly string _operationName;
            private readonly string _controllerName;
            // private readonly ILog _myLog;
    
            public LoggingOperationInvoker(IOperationInvoker baseInvoker, DispatchOperation operation)
            {
                // _myLog = myLog;
                _baseInvoker = baseInvoker;
                _operationName = operation.Name;
                _controllerName = operation.Parent.Type == null ? "[None]" : operation.Parent.Type.FullName;
            }
            private void InsertRecord(Npgsql.NpgsqlConnection faConn, string faGuid, string faUser)
            {
                try
                {
                    Npgsql.NpgsqlCommand command = new Npgsql.NpgsqlCommand("INSERT INTO switch.log(guid,username, method, ctime, ident) values(@guid,@username,@method,@ctime,@ident)", faConn);
                    command.Parameters.Add("guid", faGuid);
                    command.Parameters.Add("username", faUser);
                    command.Parameters.Add("method", _operationName + ":" + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
                    command.Parameters.Add("ctime", DateTime.Now);
                    command.Parameters.Add("ident", null);
                    command.ExecuteNonQuery();
                }
                catch (Exception ex) { }
            }
            private void InsertRecord(Npgsql.NpgsqlConnection faConn, string faGuid, string faUser,string faError,string faStacktrace)
            {
                try
                {
                    Npgsql.NpgsqlCommand command = new Npgsql.NpgsqlCommand("INSERT INTO switch.log(guid,username, method, ctime, ident,error,stacktrace) values(@guid,@username,@method,@ctime,@ident,@error,@stacktrace)", faConn);
                    command.Parameters.Add("guid", faGuid);
                    command.Parameters.Add("username", faUser);
                    command.Parameters.Add("method", _operationName + ":" + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
                    command.Parameters.Add("ctime", DateTime.Now);
                    command.Parameters.Add("ident", null);
                    if (faError.Length > 255)
                        faError = faError.Substring(0, 255);
                    command.Parameters.Add("error", faError);
                    if (faStacktrace.Length > 255)
                        faStacktrace = faStacktrace.Substring(0,255);
                    command.Parameters.Add("stacktrace", faStacktrace);
    
                    command.ExecuteNonQuery();
                }
                catch (Exception ex) { }
            }
            public object Invoke(object instance, object[] inputs, out object[] outputs)
            {
                Guid guid = Guid.NewGuid();
                string user = null;
                if (OperationContext.Current != null)
                {
                    var props = OperationContext.Current.IncomingMessageProperties;
                    var endpointProperty = props[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
                    if (endpointProperty != null)
                    {
                        user = endpointProperty.Address;
                    }
                }
                object result = null;
                using (Npgsql.NpgsqlConnection conn = new Npgsql.NpgsqlConnection(HelpMethods.GetConnectionString(TypeConnectionstring.SwitchCadTechWeb)))
                {
                    try
                    {
                        if (_operationName == "GB")
                        {
                            int cl = 11;
                            cl++;
                        }
                        conn.Open();
                        Npgsql.NpgsqlCommand command = new Npgsql.NpgsqlCommand("INSERT INTO switch.log(guid,username, method, ctime, ident) values(@guid,@username,@method,@ctime,@ident)", conn);
                        command.Parameters.Add("guid", guid);
                        command.Parameters.Add("username", user);
                        command.Parameters.Add("method", _operationName + ":" + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
                        command.Parameters.Add("ctime", DateTime.Now);
                        command.Parameters.Add("ident", null);
                        command.ExecuteNonQuery();
    
                    }
                    catch (Exception ex) { }
                    // _myLog.Log("Method " + _operationName + " of class " + _controllerName + " called");
    
                    try
                    {
                        result = _baseInvoker.Invoke(instance, inputs, out outputs);
                        // connection = new Npgsql.NpgsqlConnection();
                    }
                    catch (FaultException<CTAutorizationFault> ex1)
                    {
                        InsertRecord(conn, guid.ToString(), user, ex1.Message, ex1.StackTrace);
                        throw new FaultException<CTAutorizationFault>(new CTAutorizationFault(ex1.Message), ex1.Reason);
                    }
                    catch (FaultException<CTAccessError> ex2)
                    {
                        InsertRecord(conn, guid.ToString(), user, ex2.Message, ex2.StackTrace);
                        throw new FaultException<CTAccessError>(new CTAccessError(ex2.Message), ex2.Reason);
                    }
                    catch (Exception ex)
                    {
                        InsertRecord(conn, guid.ToString(), user, ex.Message, ex.StackTrace);
                        throw new FaultException(ex.Message);
                    }
                    InsertRecord(conn, guid.ToString(), user);
                    try
                    {
                       if (conn.State == System.Data.ConnectionState.Open)
                        conn.Close();
                    }
                    catch(Exception ex)
                    {
    
                    }
                }
                return result;
            }
    
            public object[] AllocateInputs() { return _baseInvoker.AllocateInputs(); }
    
            public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
            {
                Guid guid = Guid.NewGuid();
                string user = null;
                if (OperationContext.Current != null)
                {
                    var props = OperationContext.Current.IncomingMessageProperties;
                    var endpointProperty = props[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
                    if (endpointProperty != null)
                    {
                        user = endpointProperty.Address;
                    }
                }
                using (Npgsql.NpgsqlConnection conn = new Npgsql.NpgsqlConnection(HelpMethods.GetConnectionString(TypeConnectionstring.SwitchCadTechWeb)))
                {
                    try
                    {
                        if (_operationName == "GB")
                        {
                            int cl = 11;
                            cl++;
                        }
                        conn.Open();
                        Npgsql.NpgsqlCommand command = new Npgsql.NpgsqlCommand("INSERT INTO switch.log(guid,username, method, ctime, ident) values(@guid,@username,@method,@ctime,@ident)", conn);
                        command.Parameters.Add("guid", guid);
                        command.Parameters.Add("username", user);
                        command.Parameters.Add("method", _operationName);
                        command.Parameters.Add("ctime", DateTime.Now);
                        command.Parameters.Add("ident", null);
                        command.ExecuteNonQuery();
                    }
                    catch (Exception ex) { }
                    finally
                    {
                        if (conn.State == System.Data.ConnectionState.Open)
                            conn.Close();
                    }
                }
                state = guid + "_" + user;
                IAsyncResult result = _baseInvoker.InvokeBegin(instance, inputs, callback, state);
                return result;
            }
    
            public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
            {
                object result1 = null;
                try
                {
                    result1 = _baseInvoker.InvokeEnd(instance, out outputs, result);
                }
                  
                catch(Exception ex)
                {
                    using (Npgsql.NpgsqlConnection conn = new Npgsql.NpgsqlConnection(HelpMethods.GetConnectionString(TypeConnectionstring.SwitchCadTechWeb)))
                    {
                        try
                        {
                            string s = result.AsyncState as string;
                            string guid = null;
                            string user = null;
                            if (s != null)
                            {
                                string[] arr = guid.Split(' ');
                                guid = arr[0];
                                user = arr[1];
                            }
                            conn.Open();
                            InsertRecord(conn, guid.ToString(), user, ex.Message, ex.StackTrace);
                        }
    
                        finally
                        {
                            if (conn.State == System.Data.ConnectionState.Open)
                                conn.Close();
                        }
                    }
                    throw new Exception(ex.Message);
                }
                    if (result != null)
                    {
                        string s = result.AsyncState as string;
                        string guid = null;
                        string user = null;
                        if (s != null)
                        {
                            string[] arr = guid.Split(' ');
                            guid = arr[0];
                            user = arr[1];
                        }
                        if (_operationName == "GB")
                        {
                            int cl = 11;
                            cl++;
                        }
                        using (Npgsql.NpgsqlConnection conn = new Npgsql.NpgsqlConnection(HelpMethods.GetConnectionString(TypeConnectionstring.SwitchCadTechWeb)))
                        {
                            try
                            {
    
                                conn.Open();
                                Npgsql.NpgsqlCommand command = new Npgsql.NpgsqlCommand("INSERT INTO switch.log(guid,username, method, ctime, ident) values(@guid,@username,@method,@ctime,@ident)", conn);
                                command.Parameters.Add("guid", guid);
                                command.Parameters.Add("username", user);
                                command.Parameters.Add("method", _operationName);
                                command.Parameters.Add("ctime", DateTime.Now);
                                command.Parameters.Add("ident", null);
                                command.ExecuteNonQuery();
                            }
    
                            finally
                            {
                                if (conn.State == System.Data.ConnectionState.Open)
                                    conn.Close();
                            }
                        }
                    }
              
                return result1;
            }
    
            public bool IsSynchronous { get { return _baseInvoker.IsSynchronous; } }
        }
    }
    
    


    13 ноября 2018 г. 9:03