Friday, May 31, 2013

WCF - SendTimeout setting in CustomBinding

Timeout in WCF can occur when WCF communication takes longer than default timeout time. There are open/close/send/receive timeout but in many cases most important timeout is SendTimeout. If wait time is expected to be long, sometimes you might want to adjust SendTimeout property. This can be adjusted in code or web.config (or app.config in case of self hosting). In this example, we have self hosting console application that hosts a simple WCF service. Typically we use BasicHttpBinding or WsHttpBinding but this example uses a CustomBinding (for some reason, not important here).
static void Main(string[] args)
{
    Uri baseAddress = new Uri("http://localhost:8899/");
    ServiceHost host = new ServiceHost(typeof(SimpleService), baseAddress);

    BasicHttpBinding basicBinding = new BasicHttpBinding("MyBasicBinding");
    BindingElementCollection bec = basicBinding.CreateBindingElements();
    bec.Find().KeepAliveEnabled = false;

    CustomBinding customBinding = new CustomBinding(bec);

    // By default, sendTimeout is 1 min
    // customBinding does not automatically inherit basicBinding attr settings
    //customBinding.SendTimeout = basicBinding.SendTimeout;            

    host.AddServiceEndpoint(typeof(ISimpleService), customBinding, "ISimple");

    Console.WriteLine("SendTimeout" + customBinding.SendTimeout);
    Console.WriteLine("ReceiveTimeout" + customBinding.ReceiveTimeout);

    host.Open();

    Console.WriteLine("WCF Service Started. Press ENTER to stop.");
    Console.ReadLine();

    host.Close();
}

app.config
<configuration>
    <system.serviceModel>
      <bindings>
        <basicHttpBinding>
          <binding name="MyBasicBinding" maxReceivedMessageSize="40960" sendTimeout="00:05:00" receiveTimeout="00:05:00">
            <readerQuotas maxStringContentLength="40960"/>
          </binding>
        </basicHttpBinding>
      </bindings>
      
    </system.serviceModel>
</configuration>

The example gets BasicHttpBinding settings from app.config, and pass bindingElements to CustomBinding. In app.config, MyBasicBinding has sendTimeout and receiveTimeout attributes. I expected that those values were copied to custom binding but it turned out that those attributes are not. By default, sendTimeout is set to 1 minute and receiveTimeout is set to 10 mins. Unless explicitly set in the code, the self hosting service above will keep default value. So in this example, the code customBinding.SendTimeout = basicBinding.SendTimeout; should be uncommented to set timeout value.

No comments:

Post a Comment