列表5.1 显示了一个没有定义任何并发或实例行为的服务,它指导WCF使用默认值,ConcurrencyMode.Single和InstanceContextMode.PerSession.当使用这些设置和一个不支持会话的绑定时,比如basicHttpBinding,WCF创建为每个它接收到的请求创建一个新的服务实例并在它自己的线程里执行代码。它在返回前会等待5秒。
列表5.1 使用默认并发和实例行为的服务
[ServiceContract]
public interface IStockService
{
[OperationContract]
double GetPrice(string ticker);
}
[ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Single, InstanceContextMode=InstanceContextMode.PerSession)]
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(5000);
return 94.85;
}
}
图片5.2显示了客户端(左边)和服务端(右边)的输出结果。客户端输出显示三个请求是同步发送的而且结果在5秒钟后返回。服务端输出显示每个客户端请求都创建一个服务类的实例并且每个请求都在它自己的线程内处理。因为basicHttpBinding不支持会话,PerSession默认行为与PerCall一样。InstanceContextMode.PerSession行为指导WCF为每一个请求生成一个新的实例,同时ConcurrencyMode.Single设置指导WCF每个实例只允许一个线程执行。

图片5.2 不支持会话的绑定的默认InstanceContextMode和ConcurrencyMode的输出结果