none
Strange OutOfmemory Exception !!! RRS feed

  • Question

  • Dear all,

    Time to time I get the following error on my on my client application which is consuming WCF services. Does anyon have som glue or idea what could it be or cause such thing happen ?:

    <Message>Exception of type 'System.OutOfMemoryException' was thrown.</Message> 
      <StackTrace>at System.Collections.Generic.List`1.set_Capacity(Int32 value) at System.Collections.Generic.List`1.EnsureCapacity(Int32 min) at System.Collections.Generic.List`1.Add(T item) at System.ServiceModel.Diagnostics.TraceXPathNavigator.AddElement(String prefix, String name, String xmlns) at System.ServiceModel.Diagnostics.PlainXmlWriter.WriteStartElement(String prefix, String localName, String ns) at System.Xml.XmlWriter.WriteElementString(String localName, String ns, String value) at System.Xml.XmlWriter.WriteElementString(String localName, String value) at System.ServiceModel.Diagnostics.DictionaryTraceRecord.WriteTo(XmlWriter xml) at System.ServiceModel.Diagnostics.DiagnosticTrace.BuildTrace(PlainXmlWriter xml, TraceEventType type, TraceCode code, String description, TraceRecord trace, Exception exception, Object source) at System.ServiceModel.Diagnostics.DiagnosticTrace.BuildTrace(TraceEventType type, TraceCode code, String description, TraceRecord trace, Exception exception, Object source, TraceXPathNavigator& navigator) at System.ServiceModel.Diagnostics.DiagnosticTrace.TraceEvent(TraceEventType type, TraceCode code, String description, TraceRecord trace, Exception exception, Object source) at System.ServiceModel.Diagnostics.DiagnosticTrace.TraceEvent(TraceEventType type, TraceCode code, String description, TraceRecord trace, Exception exception, Guid activityId, Object source) at System.ServiceModel.Diagnostics.ServiceModelActivity.TraceMilestone(TraceEventType type) at System.ServiceModel.Diagnostics.ServiceModelActivity.Stop() at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessageCleanup(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.Dispatch(MessageRpc& rpc, Boolean isOperationContextSet) at System.ServiceModel.Dispatcher.ChannelHandler.DispatchAndReleasePump(RequestContext request, Boolean cleanThread, OperationContext currentOperationContext) at System.ServiceModel.Dispatcher.ChannelHandler.HandleRequest(RequestContext request, OperationContext currentOperationContext) at System.ServiceModel.Dispatcher.ChannelHandler.AsyncMessagePump(IAsyncResult result) at System.ServiceModel.Dispatcher.ChannelHandler.OnAsyncReceiveComplete(IAsyncResult result) at System.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result) at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously) at System.ServiceModel.Channels.FramingDuplexSessionChannel.TryReceiveAsyncResult.OnReceive(IAsyncResult result) at System.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result) at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously) 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.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result) at System.Net.LazyAsyncResult.Complete(IntPtr userToken) at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken) at System.Net.Security.NegotiateStream.ProcessFrameBody(Int32 readBytes, Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.NegotiateStream.ReadCallback(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.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously) at System.ServiceModel.Channels.ConnectionStream.ReadAsyncResult.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.ServiceModel.Diagnostics.Utility.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped) at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)</StackTrace> 
      </Exception>
    I have no idea how to isolate such error. What is strange to me is that the Diagnbostics is desable and it is stil reporting some Service.Model.Diagnostics namespace...

    Thanks for help
    regards
    Serge

    Your experience is build from the one of others
    Monday, June 8, 2009 9:23 AM

All replies

  • Hi Serge,

    Are you creating a Generic.List somewhere in your code ?. Or are you returning a list in the service ?. At some point, a list is being created with the capacity constructor List(int capacity), and that number is big enough to produce an "out of memory" exception.

    Regards,
    Pablo. 


    Pablo Cibraro - http://weblogs.asp.net/cibrax
    Monday, June 8, 2009 1:15 PM
  • Yes I am using somelist in my code which is containing what i am collecting from a database. most of my services return DataTable or DataSet
    So at the begining return data might be few but at after a full days might be more.

    but what is strange, is that it is not my service which is crashing with this error, but the client application (actually a WPF) which is consuming it !!!
    I all my service I have turn On the exception to be escaladade to client apps.

    How to approch that issue then if this LIst(int capaciy) is causing this ?

    Your experience is build from the one of others
    Monday, June 8, 2009 2:57 PM
  • What is strange for me is that in the exception, just after this LIst it is mentionned something about System.ServiceModel.Diagnostics.TraceXPathNavigator.

    Could it be so that this excpetion is cause by the Dignostics log to XML file ?

    serge
    Your experience is build from the one of others
    Monday, June 8, 2009 3:04 PM
  • Oh, you are right. The exception is happening in the TraceXPathNavigator class, it looks to me like  a bug in that trace listerner.
    Pablo Cibraro - http://weblogs.asp.net/cibrax
    Monday, June 8, 2009 6:21 PM
  • hi pablo,

    When setting up my Diagnostics setting formy services, I have define for each namespace ServiceModel, serialization and IO a separate file for them has I have heard and read that this XML litner is not thread safe.

    Have you met or heard anything about a similar issue ?

    if It's a bug that I am more happy in a way that if it is not becasue it is now 2 full weeks that I am fighting with this actually and do not know anymore where to look.

    I will try to totally desable the Service doagnostics
    Or should I better change the listner to something else than XML ? any idea ?

    thanks
    serge
    Your experience is build from the one of others
    Monday, June 8, 2009 8:22 PM
  • Hi Serge,

    No, I do not think you need to define a different file for each namespace, I have never had a threading problem before for configuring the same listener and file for the whole ServiceModel namespace.

    Try first to configure a single file for the ServiceModel namespace. You should not have any problem after doing that. If you still have problems, it could be a bug in the xml trace listener.

    Regards,
    Pablo.
    Pablo Cibraro - http://weblogs.asp.net/cibrax
    Tuesday, June 9, 2009 1:17 PM
  • here is how my disgnostics part is configured :

    <system.diagnostics>
        <sources>
          <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
            <listeners>
              <add name="xml" type="System.Diagnostics.XmlWriterTraceListener" initializeData="e:\logs\ServiceModel.svclog" />
            </listeners>
          </source>
          <source name="System.IO.Log" switchValue="Information, ActivityTracing" propagateActivity="true">
            <listeners>
              <add name="xml" type="System.Diagnostics.XmlWriterTraceListener" initializeData="e:\logs\IO.svclog" />
            </listeners>
          </source>
          <source name="System.Runtime.Serialization" switchValue="Information, ActivityTracing" propagateActivity="true">
            <listeners>
              <add name="xml" type="System.Diagnostics.XmlWriterTraceListener" initializeData="e:\logs\Serialization.svclog" />
            </listeners>
          </source>
        </sources>
      </system.diagnostics>
      

    Your experience is build from the one of others
    Tuesday, June 9, 2009 9:14 PM
  • Hello I thing I manage to point out where it stops.

    In fact the OutofMemory exceptionOccurs right after a ChannelFaulted and at the point I reconstruct the service.

    here is the class where my debugger stoped when exception occurs

     public abstract class WcfServiceBase<T> : IDisposable
            where T : class, ICommunicationObject
        {
            #region Constants
            private const string USER_NAME = "admin";
            private const string PASSWORD = "admin";        
            #endregion
    
            #region Private Members
            private T _service;
            private string _endPoint;
            private ServiceMode _mode;
            //private Impersonate _currentImpersonation;
            private Mutex _mutex;
            private bool _isOpened;
            private event EventHandler _closing;
            private event EventHandler _opening;
            #endregion
    
            #region Constructor
            /// <summary>
            /// Initialize a new instance of the <c>WcfServiceBase</c> class.
            /// </summary>
            /// <param name="endPoint">The name of the service configuration end point.</param>
            /// <param name="mode">Defines the behaviour of the service manager class.</param>
            public WcfServiceBase(string endPoint, ServiceMode mode)
            {
                _service = null;
                _endPoint = endPoint;
                _mode = mode;
                _mutex = new Mutex(false, this.GetType().Name);
                //_currentImpersonation = null;
    
                // Connect if required
                if (_mode == ServiceMode.AlwaysConnected)
                    OpenCore(false);
            }
            #endregion
    
            #region Public Events
            /// <summary>
            /// Occurs after the connection has been closed.
            /// </summary>
            public event EventHandler Closing
            {
                add { _closing += value; }
                remove { _closing -= value; }
            }
    
            /// <summary>
            /// Occurs before the connection has been opened.
            /// </summary>
            public event EventHandler Opening
            {
                add { _opening += value; }
                remove { _opening -= value; }
            }
            #endregion
    
            #region Public Properties
            /// <summary>
            /// Returns a valid instance of the wcf service.
            /// </summary>
            public T Service
            {
                get
                {
                    bool result = false;
    
                    result = CheckService(false);
                    if (!result)
                    {
                        _service = CreateService(_endPoint);
                        CheckService(true);
                    }
                    return _service;
                }
            }
            #endregion
    
            #region Private Methods
            /// <summary>
            /// Try to open the specified service and try to recover it if required.
            /// </summary>
            /// <param name="service">The service to open.</param>
            /// <param name="throwOnError">Indicates if an exception must be thwown on error.</param>
            /// <returns><c>true</c> if <paramref name="service"/> could be opened; <c>false</c> if <paramref name="service"/> has been set to <c>null</c> and needs to be re-created.</returns>
            private bool CheckService(bool throwOnError)
            {
                // Do nothing the service is not yet created.
                if (_service == null)
                    return false;
    
                try
                {
                    switch (_service.State)
                    {
                        case CommunicationState.Faulted:
                            _service.Abort();
                            _service.Open();
                            break;
                        case CommunicationState.Opened:
                            //No need to close an open service ( CAL )
                            //_service.Close();
                            //_service.Open();
                            break;
                        case CommunicationState.Closed:
                            _service = CreateService(_endPoint);
                            _service.Open();
                            break;
                        case CommunicationState.Created:
                            _service.Open();
                            break;
                    }
                }
                catch
                {
                    if (_service != null && _service.State == CommunicationState.Faulted)
                        _service.Abort();
                    _service = null;
                    if (throwOnError)
                        throw;
    } <---- DEBUBGGER STOP AT THIS LINE !!!! return _service != null; } /// <summary> /// Occurs when the service first enter the closed state. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The data of the event.</param> private void Service_Closed(object sender, EventArgs e) { CloseCore(); OpenCore(false); } /// <summary> /// Occurs when the service first enter the faulted state. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The data of the event.</param> private void Service_Faulted(object sender, EventArgs e) { RecoverCloseFaultedChannel(); } /// <summary> /// Occurs when the service times out. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The data of the event.</param> private void Service_TimeOut(object sender, EventArgs e) { CloseCore(); OpenCore(false); } /// <summary> /// Opens the service. /// </summary> /// <param name="keepImpersonated">Specify wether the impersonation is kept after the method call.</param> /// <remarks>If <paramref name="keepImpersonated"/> is set to <c>true</c>. The impersonation only ends upon a call to <see cref="CloseCore"/>.</remarks> private void OpenCore(bool keepImpersonated) { bool created = false; try { // Acquire the connection mutex. _mutex.WaitOne(); try { //_currentImpersonation = new Impersonate(); try { // Re-connect if (!CheckService(false)) { created = true; _service = CreateService(_endPoint); CheckService(true); } // Initialize InitService(_service, created); // Register events to auto-reconnect if required if (_mode == ServiceMode.AlwaysConnected) { _service.Faulted += new EventHandler(Service_Faulted); _service.Closed += new EventHandler(Service_Closed); } // Finishes the impersonation if required if (!keepImpersonated) { //_currentImpersonation.Dispose(); //_currentImpersonation = null; } // All fine ! _isOpened = true; } catch { //_currentImpersonation.Dispose(); //_currentImpersonation = null; throw; } } catch { _mutex.ReleaseMutex(); throw; } } catch (Exception ex) { if (Logger.CheckException(ex, typeof(System.Security.Authentication.AuthenticationException))) Logger.Error(Messages.Data.InvalidCredentialsConnectionFailure, ex); else Logger.Error(Messages.Data.UnknownConnectionFailure, ex); throw; } } /// <summary> /// Closes the service. /// </summary> /// <remarks>If an impersonation context is still in place, it will be released.</remarks> private void CloseCore() { if (!_isOpened) return; try { if (_service != null) { // Setup an impersonation context if required //if (_currentImpersonation == null) // _currentImpersonation = new Impersonate(); // Finalize try { FinalizeService(_service); } catch { } // Unregister events if (_mode == ServiceMode.AlwaysConnected) { _service.Faulted -= new EventHandler(Service_Faulted); _service.Closed -= new EventHandler(Service_Closed); } // Close try { if (_service.State == CommunicationState.Faulted) _service.Abort(); else if (_service.State != CommunicationState.Closed && _service.State != CommunicationState.Closing) _service.Close(); } catch { _service.Abort(); } } } finally { // Closes the impersonation context if required try { //if (_currentImpersonation != null) //{ // _currentImpersonation.Dispose(); // _currentImpersonation = null; //} } catch { } finally { // Releases the connection mutex //TODO: CALTEST remote line below due the call from an unsynchrone code part _mutex.ReleaseMutex(); } _isOpened = false; } } /// <summary> /// RecoverFaultedChannel the service. /// </summary> /// <remarks>If an impersonation context is still in place, it will be released.</remarks> private void RecoverCloseFaultedChannel() { //if channel is fauly no other choice to recreate the channel _service.Faulted -= new EventHandler(Service_Faulted); _service.Closed -= new EventHandler(Service_Closed); // Re-connect if (!CheckService(false)) { _service = CreateService(_endPoint); CheckService(true); } // Initialize InitService(_service, true); // Register events to auto-reconnect if required if (_mode == ServiceMode.AlwaysConnected) { _service.Faulted += new EventHandler(Service_Faulted); _service.Closed += new EventHandler(Service_Closed); } } #endregion #region Protected Methods /// <summary> /// Opens the service and keeps the impersonation context until <see cref="Close"/> is called.. /// </summary> protected virtual void Open() { //if (_mode == ServiceMode.AlwaysConnected) // throw new InvalidOperationException(); // Raise the opening event OnOpening(EventArgs.Empty); // Open OpenCore(true); } /// <summary> /// Closes the service and releases the impersonation context. /// </summary> protected virtual void Close() { //if (_mode == ServiceMode.AlwaysConnected) // throw new InvalidOperationException(); try { CloseCore(); } finally { // Raise the closed event OnClosing(EventArgs.Empty); } } /// <summary> /// Initalizes the service just after it has been connected. /// </summary> /// <param name="service">The wcf service to initialize.</param> /// <param name="created">Indicates if <paramref name="service"/> has just been created.</param> protected virtual void InitService(T service, bool created) { } /// <summary> /// Finalizes the service just before it gets closed. /// </summary> /// <param name="service">The wcf service to finalize before closing.</param> protected virtual void FinalizeService(T service) { } /// <summary> /// Creates a new instance of the WCF service. /// </summary> /// <param name="endPoint">The name of the service configuration end point.</param> protected abstract T CreateService(string endPoint); /// <summary> /// Raise the <see cref="Closed"/> event. /// </summary> /// <param name="e">The data of the event.</param> protected virtual void OnClosing(EventArgs e) { if (_closing != null) _closing(this, e); } /// <summary> /// Raise the <see cref="Opened"/> event. /// </summary> /// <param name="e">The data of the event.</param> protected virtual void OnOpening(EventArgs e) { if (_opening != null) _opening(this, e); } #endregion #region IDisposable Members /// <summary> /// Disposes the managed and unmanaged instance members. /// </summary> public void Dispose() { if (_service != null) Close(); } #endregion }
    When checking the call stack, it comes from the Service_Faulted method. From here the service proxy is rebuild by calling the RecoverCloseFaultedChannel method which call the CheckService method in which the debugger stop.


    Can you see something strange in here ?

    regards
    serge
    Your experience is build from the one of others
    Wednesday, June 10, 2009 8:35 AM