如何缩短WCF客户端的超时时间

时间:2012-10-05 10:37:02

标签: c# wcf wcf-client

如何缩短WCF客户端的超时时间。我想定期调用一些WCF服务并检查它是否可用。我希望对服务方法的调用不超过一秒钟。我试图操纵不同的超时但在每种情况下它执行超过20秒。

下面你会找到我的代码:

服务:

[ServiceContract]
public interface ICustomerManager
{
    [OperationContract]
    void StoreCustomer(string customerName);

    [OperationContract]
    void Ping();
}
[ServiceBehavior(IncludeExceptionDetailInFaults=true)]    
public class CustomerManager : MarshalByRefObject, ICustomerManager
{
    public void StoreCustomer(string customerName)
    {
        if(customerName == null) throw new ArgumentNullException("customerName");
        Console.WriteLine(customerName + " stored.");
    }

    public void Ping()
    { 
    }
}

客户端:

var binding = new NetTcpBinding(SecurityMode.None);
binding.OpenTimeout = TimeSpan.FromSeconds(1);
binding.SendTimeout = TimeSpan.FromSeconds(1);
binding.ReceiveTimeout = TimeSpan.FromSeconds(1);
binding.CloseTimeout = TimeSpan.FromSeconds(1);
binding.ReliableSession.Enabled = true;
var bindingElements = binding.CreateBindingElements();
var tcpBindingElement = bindingElements.Find<TcpTransportBindingElement>();
tcpBindingElement.ChannelInitializationTimeout = TimeSpan.FromSeconds(1);            

var factory = new ChannelFactory<ICustomerManager>(binding, "net.tcp://10.68.117.19:9998/CustomerManager");
var customerManager = factory.CreateChannel();
var contextChannel = customerManager as IClientChannel;

contextChannel.OperationTimeout = TimeSpan.FromMilliseconds(1000);

var start = DateTime.Now;
 try
 {
     customerManager.Ping();
 }
 catch (CommunicationException)
 {
     var elapsed = DateTime.Now - start;
     Console.WriteLine("elapsed: {0}", elapsed);
 }

输出为:elapsed: 00:00:20.8662525

如何让它执行不超过一秒。

我没有为我的服务器附加代码,因为我正在测试一个不可用的情况。

我在msdn论坛link上发现了非常类似的问题,不幸的是,答案也没有用。

0 个答案:

没有答案