那些年,我们一起学WCF--(8)Single实例行为

时间:2023-03-09 15:58:47
那些年,我们一起学WCF--(8)Single实例行为

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

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

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

服务端代码:

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

执行结果如下:

那些年,我们一起学WCF--(8)Single实例行为

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

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