27

Originally:

  • I thought this was a circular reference problem........turns out it's not.
  • The problem arose from having not configured the service configurations at all.
  • Since the defaults are very low, sending lots of data will make the service collapse.

Scenario:

  • It seems I may have circular references in my WCF service, but using "[DataContract(IsReference=true)]", does nothing to help fix it.
  • I receive the error "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:01:00'."
  • Have I missed something?

Code:

[DataContract(IsReference=true)]
public class Message
{
    [DataMember]
    public string TopicName { get; set; }

    [DataMember]
    public string EventData { get; set; }

    [DataMember]
    public SerializableDictionary<string, FuturesLineAsset> FuturesLineDictionary { get; set ; }
}

Thoughts:

  • I wonder if it's because I have a class FuturesAsset, that has a property of type BindableDictionary (THIS IS A CUSTOM OBJECT), and that property holds a list of FuturesLinesAssets.
  • See below:

Parent:

public class FuturesAsset
{
    public string AssetName { get; set; }
    public BindableDictionary<string, FuturesLineAsset> AssetLines { get; private set; }

    public FuturesAsset()
    {
        AssetLines = new BindableDictionary<string, FuturesLineAsset>();
    }

    public FuturesAsset(string assetName)
    {
        AssetLines = new BindableDictionary<string, FuturesLineAsset>();
        AssetName = assetName;
    }
}

Child:

public class FuturesLineAsset
{

    public string ReferenceAsset { get; set; }
    public string MID { get; set; }
    public double LivePrice { get; set; }
    public DateTime UpdateTime { get; set; }
    public DateTime LastContributedTime { get; set; }
    public double Spread { get; set; }
    public double Correlation { get; set; }
    public DateTime Maturity { get; set; }
    public double ReferenceCurve { get; set; }

    public FuturesLineAsset(string mID, string referenceAsset, double livePrice)
    {
        MID = mID;
        ReferenceAsset = referenceAsset;
        ReutersLivePrice = livePrice;
    }
}
4
  • How do you get from 'Socket error' to a circular reference? Do you have any error message you could add to the post? Aug 9, 2010 at 16:15
  • Because when I googled the error message I got lots of results talking about circular references. Also, the error only occurs when I try and send ALOT of data, otherwise it works fine.
    – Goober
    Aug 9, 2010 at 16:17
  • Check this anwer. It is relevant. WCF + NetTcp: high load make the channel stop working (calls/second rate) Feb 6, 2020 at 22:55
  • In my case, this error is caused by application pool recycle. Sep 2, 2021 at 6:39

8 Answers 8

23

This error can be caused by a number of things. While it was a timing issue in this case, it usually has nothing to do with timings, especially if the error is received immediately. Possible reasons are:

  • The objects used as parameters or return types in your contract don't have parameterless constructors and are not decorated with the DataContract attribute. Check the classes used as parameters or return types, but also all the types used by the public properties of those classes. If you implement a constructor with parameters for one of those classes, the compiler will not add the default parameterless constructor for you anymore, so you will need to add that yourself.
  • The default limits defined in service configuration are too low (MaxItemsInObjectGraph, MaxReceivedMessageSize, MaxBufferPoolSize, MaxBufferSize, MaxArrayLength).
  • Some public properties of your DataContract objects are read-only. Make sure all public properties have both getters and setters.
7
  • 1
    I had this error with the return object containing properties with decimals being out of bounds and enums with invalid values.
    – pauloya
    Nov 15, 2013 at 15:03
  • 3
    Passing a DataTable through without a .TableName, or an empty table without data (new DataTable()) can also cause this. Feb 24, 2014 at 19:13
  • 2
    I had this error and the root cause was WCF. When I switched away from WCF the problem disappeared.
    – pettys
    Apr 24, 2015 at 17:58
  • I know this doesn't apply to the original code but I had this error and found the problem to be ReadOnly properties on my DataContract objects. I gave them all setters too e.g. {get; set;} and it works fine
    – G Lewis
    Nov 1, 2016 at 11:36
  • @GLewis Good catch! I can't believe it took that long for someone to come up with this. I updated my answer accordingly. Nov 1, 2016 at 19:08
15

that exception is not related to Circular Reference, it's just purely timing out as you try to pump tons of data over the wire.

The default values that comes with WCF are very very low (these have been changed in WCF 4 I believe). Have a read on these two blog posts, they should give you an idea on how to dethrottle your service:

Creating high performance WCF services

How to throttle a Wcf service, help prevent DoS attacks, and maintain Wcf scalability

Update: also, there are a number of different timeouts in the WCF configuration and depending whether it's the client or server you're talking about you need to update a different timeout clause... have a read of this thread on what each one means and you should be able to figure out which one you need to bump up. Or, you could just set every timeout to int.max if you don't really care if a call can take a loong time to complete.

4
  • 1
    FANTASTIC YOU WERE CORRECT MY GOOD MAN!
    – Goober
    Aug 9, 2010 at 17:01
  • Damn, 2nd link is dead.
    – Grahame A
    Sep 21, 2013 at 14:31
  • Is there a mirror for the second link? Nov 21, 2013 at 21:16
  • 1
    added a cached version of the link
    – Lockszmith
    Apr 25, 2014 at 16:27
5

Had this problem with a long intialisation process that was being called from the OnStart event of a Windows Service Host installer. Fixed by setting the security mode and timeouts for the TCP binding.

            // Create a channel factory.
            NetTcpBinding b = new NetTcpBinding();
            b.Security.Mode = SecurityMode.Transport;
            b.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
            b.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;

            b.MaxReceivedMessageSize = 1000000;
            b.OpenTimeout = TimeSpan.FromMinutes(2);
            b.SendTimeout = TimeSpan.FromMinutes(2);
            b.ReceiveTimeout = TimeSpan.FromMinutes(10);
0
3

This issue can also be due to not cleaning up the WCF client when your done using it. In our system, we use the disposable pattern along with wrapping all function calls into the system to allow for proper cleanup and logging. We use a version of the following class:

    public class WcfWrapper : IDisposable
    {
        private readonly OperationContextScope _operationContextScope;
        private readonly IClientChannel _clientChannel;

        public WcfWrapper(IClientChannel clientChannel)
        {
            _clientChannel = clientChannel;
            _operationContextScope = new OperationContextScope(_clientChannel);
        }



        public void Dispose()
        {
            _operationContextScope.Dispose();
        }


        public T Function<T>(Func<T> func)
        {
            try
            {
                var result = func();
                _clientChannel.Close();
                return result;
            }
            catch (Exception ex)
            {
                KTrace.Error(ex);
                _clientChannel.Abort();
                throw;
            }

        }

        public void Procedure(Action action)
        {
            try
            {
                action();
                _clientChannel.Close();
            }
            catch (Exception ex)
            {
                KTrace.Error(ex);
                _clientChannel.Abort();
                throw;
            }
        }
    }

}

Every WCF call we make into our service is through a defined interface class like the following one:

    public sealed class WcfLoginManager : ILoginManager
    {
        private static LoginManagerClient GetWcfClient()
        {
            return 
                new LoginManagerClient(
                    WcfBindingHelper.GetBinding(),
                    WcfBindingHelper.GetEndpointAddress(ServiceUrls.LoginManagerUri));

        }

        public LoginResponse Login(LoginRequest request)
        {
            using(var loginManagerClient = GetWcfClient())
            using (var slice = new WcfWrapper(loginManagerClient.InnerChannel))
            {
                DSTicket ticket;
                DSAccount account;
                return slice.Function(() => new LoginResponse(loginManagerClient.Login(request.accountName, request.credentials, out ticket, out account), ticket, account));
            }
        }
    }

Using this pattern, all WCF calls into the system are wrapped with either the Function or the Procedure method, allowing them to first ensure logging happens on all errors, and second to ensure the channel is closed when no errors occur but aborted if an exception happens. Finally, as it's in a using statement, the final dispose of the channel is called. In this way, errors that occur due to channels not being cleaned up properly, which will look like this error, will be prevented.

1

The WCF error:

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 ...

where timeouts reported are very close to 1 minute (e.g. 00:00:59.9680000) or 1 minute exactly (i.e. 00:01:00) can be caused by the message being too large and exceeding the settings for the binding.

This can be fixed by increasing the values in the config file, e.g.:

<binding name="MyWcfBinding" 
         maxReceivedMessageSize="10000000" 
         maxBufferSize="10000000" 
         maxBufferPoolSize="10000000" />

(example values only, you may want to tune them).

1

This exception occurred for me when I was returning an object with IEnumerable collections in it, and an exception occurred while one of the collection members was being retrieved. At that point, it's too late to catch it in your code, and presumably WCF is designed to disconnect the socket in that case because it's also too late to report an exception to the client, since it has already started streaming results.

0

In my case i was trying to instantiate a Wcf with net tcp. So, if in the bindings section of your web.config you have the "netTcpBinding" configurated like this

<bindings>
    <netTcpBinding>
        <binding name="bindingName" closeTimeout="01:10:00" openTimeout="01:10:00" receiveTimeout="01:10:00" sendTimeout="01:10:00" transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions" hostNameComparisonMode="StrongWildcard" listenBacklog="10" maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxConnections="10" maxReceivedMessageSize="2147483647" portSharingEnabled="true">
            <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="16384"/>
            <reliableSession ordered="true" inactivityTimeout="01:10:00" enabled="false"/>
            <security mode="None"/>
        </binding>
    </netTcpBinding>
</bindings>

Then, you need to configurate the service section defining the endpoints with their contract attribute using the namespace of your services interface and put the baseAddres as well, something like this

<services>
  <service behaviorConfiguration="sgiBehavior" name="Enterprise.Tecnic.SGI.OP.Wcf.OP">
    <endpoint address="" behaviorConfiguration="endPointBehavior" binding="webHttpBinding" bindingConfiguration="BindingWebHttp" name="endPointHttp" contract="Enterprise.Tecnic.SGI.OP.Interface.IOP"/>
    <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" />
    <endpoint address="" binding="netTcpBinding" bindingConfiguration="bindingName"
      name="EndpointNetTcp" contract="Enterprise.Tecnic.SGI.OP.Interface.IOP" />

    <host>
      <baseAddresses>
        <!--  <add baseAddress="http://localhost:61217/OP.svc"/> -->
        <add baseAddress="http://www.Enterprise.com/Tecnic/SGI/OP/" />
        <add baseAddress="net.tcp://www.Enterprise.com/Tecnic/SGI/OP/" />           
      </baseAddresses>
    </host>
  </service>
</services>

I spent two days with this problem, but this was the only thing that worked for me.

0

For me, using this binding will overcome the issue. It is weird that the exception message doesn't help at all.

private static Binding GetBinding()
{
    if (_binding == null)
    {
        NetTcpBinding binding = new NetTcpBinding
        {
            SendTimeout = TimeSpan.FromMinutes(60),
            OpenTimeout = TimeSpan.FromMinutes(60),
            CloseTimeout = TimeSpan.FromMinutes(60),
            ReceiveTimeout = TimeSpan.FromMinutes(60),
            Security = new NetTcpSecurity
            {
                Mode = SecurityMode.Transport,
                Transport = new TcpTransportSecurity { SslProtocols = System.Security.Authentication.SslProtocols.None }
            }
        };

        binding.MaxReceivedMessageSize = 2147483647;
        binding.MaxBufferSize = 2147483647;
        binding.MaxBufferPoolSize = 2147483647;
        binding.ReaderQuotas.MaxBytesPerRead = 2147483647;
        binding.MaxConnections = 100000;

        _binding = binding;
    }

    return _binding;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.