代码改变世界

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

2010-12-06 22:17  DanielWise  阅读(1776)  评论(1编辑  收藏  举报

当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次调用完成以后客户端关闭连接,顺序会话可以被创建。

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

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