
Single实例行为,类似于单件设计模式,所有可以客户端共享一个服务实例,这个服务实例是一个全局变量,该实例第一次被调用的时候初始化,到服务器关闭的时候停止。
设置服务为Single实例行为,只要设置 [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]即可。
下面这个代码演示了多个客户端共享一个实例,当启动多个客户端,调用服务契约方法的时候,变量NUM值一直在累加,相当于一个全局静态变量。
服务端代码:
- [ServiceContract]
- public interface ISingle
- {
- [OperationContract]
- int AddCountBySingle();
- }
- [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
- publicclass SingleImpl:ISingle,IDisposable
- {
- privateint num = 0;
- publicint AddCountBySingle()
- {
- num = num + 1;
- Console.WriteLine("当前值:"+num.ToString()+",时间:"+DateTime.Now.ToString());
- return num;
- }
- publicvoid Dispose()
- {
- Console.WriteLine("释放实例");
- }
- }
[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("释放实例");
} }
客户端代码
- privatevoid button4_Click(object sender, EventArgs e)
- {//单件实例行为
- ChannelFactory<ISingle> channelFactory = new ChannelFactory<ISingle>("WSHttpBinding_ISingle");
- ISingle client = channelFactory.CreateChannel();
- client.AddCountBySingle();
- }
private void button4_Click(object sender, EventArgs e)
{//单件实例行为
ChannelFactory<ISingle> channelFactory = new ChannelFactory<ISingle>("WSHttpBinding_ISingle");
ISingle client = channelFactory.CreateChannel();
client.AddCountBySingle();
}
此时我们启动三个客户端各调用一次方法,发现服务器端num的值一直在增加。
执行结果如下:
通过以上示例,我们看到所有客户端共享一个服务实例,该实例创建一直存在,直到服务器关闭的时候消失,增大了服务器压力,使服务器资源不能有效的利用和及时释放。