如何缩短 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 论坛链接上发现了非常相似的问题,不幸的是,那里的答案也不起作用。