我试图弄清楚为什么客户端应用程序启动后的第一个 WCF 调用比第二个调用花费更多的时间。
我做了什么来测试:
- 实现了简单的自托管 WCF 服务器和控制台客户端。
-
服务器已预热- 在运行测试之前我运行它并调用方法几次。
- 绑定是
basicHttpBinding
以减少网络和安全开销。
- 测试场景 - 启动控制台客户端应用程序,连续进行两个相同的 WCF 服务调用。
在我的测试中,第一次调用大约需要 700 毫秒,第二次调用大约需要 3 毫秒。
对于 JIT 编译器来说,几乎一秒钟似乎太长了。如果这段时间用于初始化一些复杂的基础设施,例如ObjectContext
在实体框架中,但我的代码非常简单,代理类已经编译。
我也尝试过netNamedPipeBinding
捆绑。结果证明了模式 - 第一次调用需要约 800 毫秒,第二次调用需要约 8 毫秒。
如果有人能解释为什么第一次服务呼叫需要这么长时间,我将不胜感激。
在 Win 7 64 位中测试。
我的实现如下。
合同:
[ServiceContract]
public interface ICounter
{
[OperationContract]
int Add(int num);
}
服务实施:
public class CounterService: ICounter
{
private int _value = 0;
public int Add(int num)
{
_value += num;
Console.WriteLine("Method Add called with argument {0}. Method returned {1}", num, _value);
return _value;
}
}
服务器实现:
class Program
{
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:8080/Service");
// Create the ServiceHost.
using (ServiceHost host = new ServiceHost(typeof(CounterService), baseAddress))
{
host.Open();
Console.WriteLine("The service is ready at {0}", baseAddress);
Console.WriteLine("Press <Enter> to stop the service.");
Console.ReadLine();
// Close the ServiceHost.
host.Close();
}
}
}
服务器配置:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service name="Server.CounterService">
<endpoint address="base" binding="basicHttpBinding" name="baseDefault"
contract="Contract.ICounter" />
<endpoint address="net.pipe://localhost/Service/netNamedPipe"
binding="netNamedPipeBinding" name="netNamedPipeDefault" contract="Contract.ICounter" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
客户端实施(CounterProxy
从服务引用生成):
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
using (var proxy = new CounterProxy.CounterClient(_endpointConfigurationName))
{
output = proxy.Add(1);
}
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
包含连续调用两次的代码的函数。
客户端配置:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<client>
<endpoint address="http://localhost:8080/Service/base" binding="basicHttpBinding"
contract="CounterProxy.ICounter"
name="baseDefault" />
</client>
</system.serviceModel>
</configuration>