我想弄清楚爲什麼客戶端應用程序啓動後的第一個WCF調用需要比第二個更多的時間。爲什麼第一個WCF客戶端調用較慢?
我做了什麼測試:
- 實現簡單的自承載的WCF服務器和控制檯客戶端。
- 服務器被預熱 - 我運行它並在運行測試前多次調用方法。
- 綁定爲
basicHttpBinding
以減少網絡和安全開銷。 - 測試場景 - 啓動控制檯客戶端應用程序,在一行中創建兩個完全相同的WCF服務調用。
在我的測試中,我看到〜700毫秒的第一次通話和~3毫秒的第二次通話。
對於JIT編譯器來說,差不多一秒的時間似乎太多了。如果這段時間用於初始化Entity Framework中的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>
可能加載/編譯代理對象第一次,在XML序列化器等,如果您看看輸出窗口,你應該看到類似於「Loaded assembly x54fjfj3fj」這是一個已編譯的WCF客戶端。 –
我責怪安全檢查和另外100個未知數。涉及的二進制文件比部署服務中涉及的要多。要在配置和訪問日誌中調試服務使用跟蹤器,他們將以毫秒爲單位顯示花費在什麼時間上的步驟。即使您的所有內容都是匿名的,您仍然可以看到身份驗證,過濾器等內容。 – 2012-06-02 04:46:50