WCF并发模型
1. 目的是为服务提供并发控制,通过ConcurrencyMode枚举的Single(默认),Reentrant和Multiple进行设置。
2. ServiceBehaviorAttribute控制这个设置,代码:
[ServiceBehavior(ConcurrencyMode =ConcurrencyMode.Single)]
public class CounterService:ICounterService
3. Single
(1) 当服务实例处理请求时,会对其加锁,其它的线程将会排队,除非超时
(2) 当请求结束时,锁被释放,队列中的下一个线程可以访问该对象
(3) Single并发与PerCall不会产生并发问题
(4) Single与PerSession多客户端可以并发访问,如图例:
(5) Single并发与单件(Singleton),多用户是无法同时进行访问,如图例
4. Reentrant
(1) Reentrant是可重入的单线程模式
(2) Reentrant模式主要用于当服务发起回调到客户端时的场景(当回调操作不是one-way操作时)
(3) Reentrant与Single在回调中的对比图例,实例模型为percall:
(4) Reentrancy, PerSession与Singletons。对于persession和Singletons而言,当进行回调的时候,别的请求可以继续进入进行访问操作,而对于重入来的请求如果有请求了,那么重入过来的请求进行等待。图例:
5. Multiple
(1) 当服务实例处理请求时,系统不会自动加锁
(2) 需要自定义实现多线程保护
WCF限流设置
1. ServiceThrottleBehavior提供了很多吞吐量控制的设置:
(1)MaxConcurrentCalls: 限制并发请求– 缺省为16
(2)MaxConcurrentInstances: 限制服务实例的数量– 缺省为int.MaxValue
(3)MaxConcurrentSessions:限制活动会话数量,包括传输,可靠性与安全会话和应用程序会话– 缺省10
2. 配置/程序代码设置:
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehavior">
<serviceThrottling maxConcurrentCalls="30" maxConcurrentInstances="30" maxConcurrentSessions="1000" />
</behavior>
</serviceBehaviors>
</behaviors>
ServiceHost host = new ServiceHost(typeof(Counters.CounterService));
ServiceThrottle throttle = host.Description.Behaviors.Find<ServiceThrottle>();
if (throttle != null)
{
throttle.MaxConcurrentCalls = 30;
throttle.MaxConcurrentInstances = 30;
throttle.MaxConcurrentSessions = 100;
}
3. 限流与PerCall
(1) MaxConcurrentCalls与MaxConcurrentInstances控制每个服务的吞吐量
(2) MaxConcurrentSessions支持传输,可靠性,或者安全会话
4. 限流与PerSession
(1) MaxConcurrentCalls控制吞吐量
(2) MaxConcurrentInstances应该大于等于MaxConcurrentSessions后者支持传输,可靠性,或者安全会话,以及应用程序会话
5. 限流与单件(Singleton)
(1) MaxConcurrentCalls控制吞吐量
(2) MaxConcurrentInstances与该模式无关
(3) MaxConcurrentSessions依赖于对于传输,可靠性,安全以及应用程序会话的支持