我理解ClientBase<>为通道工厂添加了内置缓存。但它应该是.Net(4.5)的更高版本:more here
现在,我有一个简单的示例项目,看看是否重用了同一个客户端,或者为每次调用创建了一个新的来分析所花费的时间。以下是一些代码段:
[ServiceContract]
public interface ISoapService
{
[OperationContract]
string GetData(int value);
}
客户代码:
private static void NonCachedVersion()
{
Console.WriteLine("Non-Cached Version");
for (int i = 0; i < 5; i++)
{
var watch = Stopwatch.StartNew();
using (var client = new SoapServiceReference.SoapServiceClient())
{
client.GetData(5);
watch.Stop();
}
Console.WriteLine("{0}: {1}ms", i, watch.ElapsedMilliseconds);
}
}
private static void CachedVersion()
{
Console.WriteLine("Cached Version");
using (var client = new SoapServiceReference.SoapServiceClient())
{
for (int i = 0; i < 5; i++)
{
var watch = Stopwatch.StartNew();
client.GetData(5);
watch.Stop();
Console.WriteLine("{0}: {1}ms", i, watch.ElapsedMilliseconds);
}
client.Close();
}
}
打电话给他们:
static void Main(string[] args)
{
NonCachedVersion();
Console.WriteLine();
CachedVersion();
Console.ReadLine();
}
这是输出:
Non-Cached Version
0: 2030ms
1: 22ms
2: 19ms
3: 21ms
4: 18ms
Cached Version
0: 19ms
1: 7ms
2: 7ms
3: 7ms
4: 8ms
此外,如果我首先调用缓存版本然后调用非缓存版本,则时间如下:
Cached Version
0: 2275ms
1: 13ms
2: 8ms
3: 8ms
4: 8ms
Non-Cached Version
0: 19ms
1: 18ms
2: 18ms
3: 18ms
4: 19ms
因此,它本质上是第一个昂贵的调用,其余似乎正在使用某种缓存。
所以,很少有事情: