Прерывистый отказ службы WCF

У меня есть служба WCF, которая прерывается с перерывами. Когда это не удается, я вижу из информации svctraceviewer, что два отдельных потока запрашивают "информацию о соединении" одновременно. Один из потоков успешно завершен, а другой не удается выполнить эту ошибку: "При использовании WebContentTypeMapper возникло непредвиденное исключение". Запросы идентичны, за исключением некоторых значений в теле POST, поэтому я предполагаю, что реальная проблема связана с конфликтом при запросе "информации о соединении". Я не смог найти какую-либо информацию о том, что делает среда выполнения WCF во время этого запроса информации о соединении.

Я должен отметить, что клиентский POSTs некодированный XML и использует заголовок HTTP Content-Type приложения /xml, поэтому у меня есть пользовательская привязка для приема потока xml. Я не могу изменить способ отправки POST на мой сервис.

Мысли?

web.config

<system.servicemodel>
 <services>
 <service name="SAPCallbackHandlerNamespace.SAPCallbackHandler" behaviorconfiguration="">
 <endpoint address="" binding="customBinding" contract="SAPCallbackHandlerNamespace.ISAPCallbackHandler" behaviorconfiguration="webBehavior" bindingconfiguration="customBindingHTTP">
 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange">
 <host>
 <baseaddresses>
 <add baseaddress="http://localhost/service.svc/">
 </add></baseaddresses>
 </host>
 </endpoint></endpoint></service>
 </services>
 <bindings>
 <custombinding>
 <binding name="customBindingHTTP">
 <webmessageencoding webcontenttypemappertype="SAPCallbackHandlerNamespace.RawContentTypeMapper, SAPCallbackHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
 <httptransport manualaddressing="true" maxreceivedmessagesize="524288000" transfermode="Streamed">
 </httptransport></webmessageencoding></binding>
 </custombinding>
 </bindings>
 <behaviors>
 <servicebehaviors>
 <behavior>
 <servicemetadata httpgetenabled="true" httpsgetenabled="true">
 <servicedebug includeexceptiondetailinfaults="false">
 </servicedebug></servicemetadata></behavior>
 </servicebehaviors>
 <endpointbehaviors>
 <behavior name="webBehavior">
 <webhttp>
 </webhttp></behavior>
 </endpointbehaviors>
 </behaviors>
</system.servicemodel>

Код

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Single)]
[DataContract]
public class SAPCallbackHandler : ISAPCallbackHandler
{
 public string ParseIncomingXML(Stream incomingXML)
 {
 ...
 }
}

public class RawContentTypeMapper : WebContentTypeMapper
{
 public override WebContentFormat GetMessageFormatForContentType(string contentType)
 {
 if (contentType.Contains("text/xml") || contentType.Contains("application/xml"))
 {
 return WebContentFormat.Raw;
 }
 else
 {
 return WebContentFormat.Default;
 }
 }
}

Интерфейс

[ServiceContract]
public interface ISAPCallbackHandler
{
 [OperationContract]
 [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare)]
 string ParseIncomingXML(Stream incomingXML);
}

Трассировка информации о соединении:

<e2etraceevent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent">
 <system xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system">
 <eventid>262168</eventid>
 <type>3</type>
 <subtype name="Information">0</subtype>
 <level>8</level>
 <timecreated systemtime="2013-11-04T16:52:26.3746976Z">
 
 <correlation activityid="{00000000-0000-0000-0000-000000000000}">
 <execution processname="w3wp" processid="3992" threadid="7">
 <channel>
 <computer>TX-APP-J01</computer>
 </channel></execution></correlation></timecreated></system>
 <applicationdata>
 <tracedata>
 <dataitem>
 <tracerecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" severity="Information">
 <traceidentifier>http://msdn.microsoft.com/en-US/library/System.ServiceModel.Channels.ConnectToIPEndpoint.aspx</traceidentifier>
 <description>Connection information.</description>
 <appdomain>/LM/W3SVC/2/ROOT-1-130280558217413872</appdomain>
 System.ServiceModel.Activation.HostedHttpTransportManager/4720237
 <extendeddata xmlns="http://schemas.microsoft.com/2006/08/ServiceModel/DictionaryTraceRecord">
 <localendpoint>10.198.147.12:80</localendpoint>
 <remoteendpoint>163.231.6.69:24074</remoteendpoint>
 </extendeddata>
 </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="2013-11-04T16:52:26.4370984Z">
 
 <correlation activityid="{00000000-0000-0000-0000-000000000000}">
 <execution processname="w3wp" processid="3992" threadid="7">
 <channel>
 <computer>TX-APP-J01</computer>
 </channel></execution></correlation></timecreated></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/2/ROOT-1-130280558217413872</appdomain>
 <exception>
 <exceptiontype>System.ServiceModel.CommunicationException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</exceptiontype>
 <message>An unexpected exception was encountered when using the WebContentTypeMapper.</message>
 <stacktrace> at System.ServiceModel.Channels.WebMessageEncoderFactory.WebMessageEncoder.TryGetContentTypeMapping(String contentType, WebContentFormat& format)
 at System.ServiceModel.Channels.WebMessageEncoderFactory.WebMessageEncoder.IsContentTypeSupported(String contentType)
 at System.ServiceModel.Channels.HttpInput.ValidateContentType()
 at System.ServiceModel.Channels.HttpInput.ParseMessageAsyncResult.BeginParse()
 at System.ServiceModel.Channels.HttpInput.BeginParseIncomingMessage(HttpRequestMessage httpRequestMessage, AsyncCallback callback, Object state)
 at System.ServiceModel.Channels.HttpPipeline.EmptyHttpPipeline.BeginParseIncomingMessage(AsyncCallback asynCallback, Object state)
 at System.ServiceModel.Channels.HttpPipeline.EmptyHttpPipeline.BeginProcessInboundRequest(ReplyChannelAcceptor replyChannelAcceptor, Action dequeuedCallback, AsyncCallback callback, Object state)
 at System.ServiceModel.Channels.HttpChannelListener'1.HttpContextReceivedAsyncResult'1.ProcessHttpContextAsync()
 at System.ServiceModel.Channels.HttpChannelListener'1.BeginHttpContextReceived(HttpRequestContext context, Action acceptorCallback, AsyncCallback callback, Object state)
 at System.ServiceModel.Activation.HostedHttpTransportManager.HttpContextReceived(HostedHttpRequestAsyncResult result)
 at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest()
 at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest()
 at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequest(Object state)
 at System.Runtime.IOThreadScheduler.ScheduledOverlapped.IOCallback(****** errorCode, ****** numBytes, NativeOverlapped* nativeOverlapped)
 at System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(****** error, ****** bytesRead, NativeOverlapped* nativeOverlapped)
 at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(****** errorCode, ****** numBytes, NativeOverlapped* pOVERLAP)
</stacktrace>
 <exceptionstring>System.ServiceModel.CommunicationException: An unexpected exception was encountered when using the WebContentTypeMapper. ---> System.IO.IOException: The process cannot access the file 'c:\sapqueueservice\log.txt' because it is being used by another process.
 at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
 at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
 at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
 at System.IO.FileStream..ctor(String path, FileMode mode)
 at SAPCallbackHandlerNamespace.RawContentTypeMapper.GetMessageFormatForContentType(String contentType)
 at System.ServiceModel.Channels.WebMessageEncoderFactory.WebMessageEncoder.TryGetContentTypeMapping(String contentType, WebContentFormat& format)
 --- End of inner exception stack trace ---</exceptionstring><innerexception><exceptiontype>System.IO.IOException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</exceptiontype><message>The process cannot access the file 'c:\sapqueueservice\log.txt' because it is being used by another process.</message><stacktrace> at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
 at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
 at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
 at System.IO.FileStream..ctor(String path, FileMode mode)
 at SAPCallbackHandlerNamespace.RawContentTypeMapper.GetMessageFormatForContentType(String contentType)
 at System.ServiceModel.Channels.WebMessageEncoderFactory.WebMessageEncoder.TryGetContentTypeMapping(String contentType, WebContentFormat& format)</stacktrace><exceptionstring>System.IO.IOException: The process cannot access the file 'c:\sapqueueservice\log.txt' because it is being used by another process.
 at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
 at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
 at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
 at System.IO.FileStream..ctor(String path, FileMode mode)
 at SAPCallbackHandlerNamespace.RawContentTypeMapper.GetMessageFormatForContentType(String contentType)
 at System.ServiceModel.Channels.WebMessageEncoderFactory.WebMessageEncoder.TryGetContentTypeMapping(String contentType, WebContentFormat& format)</exceptionstring>
 </innerexception>
 </exception>
 </tracerecord>
 </dataitem>
 </tracedata>
 </applicationdata>
</e2etraceevent>

Выполняется служба: IIS 7.5,.NET 4.5, Windows Server 2008 R2

1 ответ

Это сообщение выделяется:

System.IO.IOException: процесс не может получить доступ к файлу 'c:\sapqueueservice\log.txt', потому что он используется другим процессом.

Похоже, что процесс блокирует этот файл.

Попробуйте использовать Process Explorer, чтобы узнать, какой процесс имеет дескриптор на нем.

licensed under cc by-sa 3.0 with attribution.