Single实例行为,类似于单件设计模式,所有可以客户端共享一个服务实例,这个服务实例是一个全局变量,该实例第一次被调用的时候初始化,到服务器关闭的时候停止。

设置服务为Single实例行为,只要设置 [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]即可。

下面这个代码演示了多个客户端共享一个实例,当启动多个客户端,调用服务契约方法的时候,变量NUM值一直在累加,相当于一个全局静态变量。

     服务端代码:

  1. [ServiceContract] 
  2. public  interface ISingle 
  3.   { 
  4.       [OperationContract] 
  5.       int AddCountBySingle(); 
  6.   } 
  7.  
  8.   [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] 
  9.   publicclass SingleImpl:ISingle,IDisposable 
  10.   { 
  11.       privateint num = 0; 
  12.       publicint AddCountBySingle() 
  13.       { 
  14.           num = num + 1; 
  15.           Console.WriteLine("当前值:"+num.ToString()+",时间:"+DateTime.Now.ToString()); 
  16.           return num; 
  17.       } 
  18.  
  19.       publicvoid Dispose() 
  20.       { 
  21.           Console.WriteLine("释放实例"); 
  22.       } 
  23.  
  24.   } 
  [ServiceContract]
   public  interface ISingle
    {
        [OperationContract]
        int AddCountBySingle();
    }

    [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
    public class SingleImpl:ISingle,IDisposable
    {
        private int num = 0;
        public int AddCountBySingle()
        {
            num = num + 1;
            Console.WriteLine("当前值:"+num.ToString()+",时间:"+DateTime.Now.ToString());
            return num;
        }

        public void Dispose()
        {
            Console.WriteLine("释放实例");
        }

    }

     客户端代码

  1. privatevoid button4_Click(object sender, EventArgs e) 
  2.      {//单件实例行为 
  3.          ChannelFactory<ISingle> channelFactory = new ChannelFactory<ISingle>("WSHttpBinding_ISingle"); 
  4.          ISingle client = channelFactory.CreateChannel(); 
  5.          client.AddCountBySingle(); 
  6.      } 
   private void button4_Click(object sender, EventArgs e)
        {//单件实例行为
            ChannelFactory<ISingle> channelFactory = new ChannelFactory<ISingle>("WSHttpBinding_ISingle");
            ISingle client = channelFactory.CreateChannel();
            client.AddCountBySingle();
        }

    此时我们启动三个客户端各调用一次方法,发现服务器端num的值一直在增加。

     执行结果如下:

     

   通过以上示例,我们看到所有客户端共享一个服务实例,该实例创建一直存在,直到服务器关闭的时候消失,增大了服务器压力,使服务器资源不能有效的利用和及时释放。

    demo: http://download.csdn.net/detail/zx13525079024/4596356

posted on 2013-12-23 14:19  gejianhua  阅读(286)  评论(0编辑  收藏  举报