【发布时间】:2011-05-13 19:41:53
【问题描述】:
我是 WCF 的新手,有一个性能问题。我在客户端执行以下代码:
try
{
for (int i = 0; i < 20; i++)
{
stopwatch.Reset();
stopwatch.Start();
var psn = client.GetPsnByPsnId(21);
var psnList = client.GetPsnBySmartBizClientId(2);
var container = client.GetContainerByContainerId(3);
var containerList = client.GetContainerBySmartBizClientId(2);
stopwatch.Stop();
Console.WriteLine(string.Format("Pass # {0} completed in {1} milliseconds", i + 1,stopwatch.ElapsedMilliseconds));
}
}
catch (FaultException exception)
{
MessageBox.Show(string.Format("Error occurred. The error message is {0}", exception.Message));
}
finally
{
client.Close();
client = null;
}
此代码使用 .NET 4.0 下的 HTTP 绑定命中作为 Windows 服务托管的 WCF 服务。我遇到的问题是这个。第一次通过循环,在第一个 WCF 调用 (client.GetPsnByPsnID()) 上,有一个非常显着的延迟,实际上是 10 多秒。但是,在第一次调用之后,每个后续调用,每次通过循环,都需要
有人知道什么可能导致初始延迟吗?
编辑:这是 Windows 服务的 OnStart 代码:
protected override void OnStart(string[] args)
{
serviceHost = new ServiceHost(typeof(ServiceMethods),new Uri("http://111.111.111.111:1111/Psn"));
// Add an endpoint and the methods the endpoint will support.
serviceHost.AddServiceEndpoint(typeof(IServiceMethods), WcfConfiguration.GenerateBinding(Enumerations.WcfBindingType.HTTP), "");
WcfConfiguration.CreateMexData(serviceHost);
serviceHost.Open();
}
这里是 GenerateBinding 方法:
public static System.ServiceModel.Channels.Binding GenerateBinding(Enumerations.WcfBindingType bindingType)
{
System.ServiceModel.Channels.Binding binding = null;
BasicHttpBinding httpBinding = new BasicHttpBinding();
httpBinding.Security.Mode = ((bindingType == Enumerations.WcfBindingType.HTTP) ? BasicHttpSecurityMode.None : BasicHttpSecurityMode.Transport);
httpBinding.OpenTimeout = new TimeSpan(0, 0, 30);
httpBinding.SendTimeout = new TimeSpan(0, 0, 30);
httpBinding.ReceiveTimeout = new TimeSpan(0, 0, 30);
httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
httpBinding.ReaderQuotas.MaxStringContentLength = httpBinding.ReaderQuotas.MaxStringContentLength;
httpBinding.MaxReceivedMessageSize = httpBinding.MaxReceivedMessageSize;
httpBinding.ReaderQuotas.MaxArrayLength = 1048576;
httpBinding.MaxBufferSize = httpBinding.MaxBufferSize;
binding = httpBinding;
break;
}
return binding;
}
public static void CreateMexData(ServiceHost host)
{
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
host.Description.Behaviors.Add(behavior);
host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
}
【问题讨论】:
-
您的服务和/或 WCF 主机的
OnStart方法中是否有重要代码? -
您的服务是事务性的吗?
-
@mellamokb - 我已经添加了 OnStart 代码。