WCF 第五章 控制并发会话的数量

当InstancingMode被设置成PerSession时,WCF为每个连接到服务端的会话创建一个实例。为了控制连接到一个服务端的会话数量,可以使用maxConcurrentSessions行为。当达到最大值时,下一个客户端尝试创建的会话将会阻塞直到另外一个会话关闭。这个设置对限制可以连接到服务端的用户(或客户端或服务器端)的数目是很有用的。

  列表5.11显示了一个使用InstanceContextMode.PerSession和ConcurrencyMode.Multiple行为的服务。服务操作花费20秒钟完成。

列表5.11 使用InstanceContextMode.PerSession和ConcurrencyMode.Multiple行为的服务

    [ServiceContract(SessionMode=SessionMode.Required)]
    public interface IStockService
    {
        [OperationContract]
        double GetPrice(string ticker);
    }

    [ServiceBehavior(InstanceContextMode= InstanceContextMode.PerSession, 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.12显示了服务端的app.config.maxConcurrentSessions行为设置为5,意味着在同一时间从客户端到服务端的会话数量至多有5个。注意这里使用了wsHttpBinding而不是basicHttpBinding因为后者不支持会话。

列表5.12 使用maxConcurrentSessions控制并发

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <bindings />
        <behaviors>
            <serviceBehaviors>
                <behavior name="throttling">
                  <serviceThrottling maxConcurrentSessions="5"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <services>
            <service behaviorConfiguration="throttling" name="Services.StockService">
                <endpoint address="" binding="wsHttpBinding" contract="Services.IStockService" />
                <host>
                    <baseAddresses>
                        <add baseAddress="http://localhost:8000/stockservice" />
                    </baseAddresses>
                </host>
            </service>
        </services>
    </system.serviceModel>
</configuration>

  图片5.8显示了列表5.7中客户端(左边)和服务端(右边)的输出结果。在客户端,当程序启动时立即进行10次调用。在那些10次调用中,5个结果在20秒钟后返回而剩下的5个结果在另外20秒钟后返回。在服务端输出,注意5个会话被创建同时5次对GetPrice的调用在客户端调用服务端时被立即执行。在那5次调用完成以后客户端关闭连接,顺序会话可以被创建。

2010120622162750.png

图片5.8 控制并发会话数量的输出结果

图片5.8 控制并发会话的输出结果

转载于:https://www.cnblogs.com/danielWise/archive/2010/12/06/1898290.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值