当InstancingMode设置成Single时,WCF在宿主内创建一个单一的实例,不考虑有多少客户端被创建。当ConcurrencyMode设置成Multiple时,WCF为每个请求创建一个线程(取决于系统上限)以实现服务方法的并行执行。为了减少这个,maxConcurrentCalls行为控制有多少个并发调用可以激活。
列表5.9 显示了一个使用InstanceContextMode.Single和ConcurrencyMode.Multiple的服务行为。服务操作花费20秒完成。
列表5.9 使用InstanceContextMode.Single和ConcurrencyMode.Multiple的行为的服务
[ServiceContract] public interface IStockService { [OperationContract] double GetPrice(string ticker); } [ServiceBehavior(InstanceContextMode= InstanceContextMode.Single, ConcurrencyMode=ConcurrencyMode.Multiple)] public class StockService : IStockService { StockService() { Console.WriteLine("{0}:Created new instance of StockService on thread", DateTime.Now); } public double GetPrice(string ticker) { Console.WriteLine("{0}: GetPrice called on thread {1}", DateTime.Now, Thread.CurrentThread.ManagedThreadId); Thread.Sleep(20000); return 94.85; } }
列表5.10 显示了服务的app.config文件。maxConcurrentCalls行为设置成5,意味着在同一时间不可以再激活多于5个调用。
列表5.10 使用maxConcurrentCalls控制并发
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <bindings /> <behaviors> <serviceBehaviors> <behavior name="throttling"> <serviceThrottling maxConcurrentCalls="5"/> </behavior> </serviceBehaviors> </behaviors> <services> <service behaviorConfiguration="throttling" name="Services.StockService"> <endpoint address="" binding="basicHttpBinding" contract="Services.IStockService" /> <host> <baseAddresses> <add baseAddress="http://localhost:8000/stockservice" /> </baseAddresses> </host> </service> </services> </system.serviceModel> </configuration>
图片5.7显示了列表5.7中的客户端(左边)和服务端(右边)输出。在客户端,注意当程序启动时10次调用立即开始。在这10次调用中,5个结果在20秒钟后返回而剩下的5个结果在另外20秒钟后返回。在服务端输出,注意只有一个实例被创建。也要注意5次对GetPrice的调用立刻执行,每个都在它们自己的线程里执行。当这5个线程结束后,线程被重用同时客户端的顺序请求被处理。
图片5.7 控制并发调用数量的输出结果