WCF PreSession模式保持调用状态

WCF开发工具是.NET Framework 3.5的一个重要组成部件。它的出现在一定程度上改变了开发人员的编程习惯,为开发人员带来了非常大帮助。在这里我们将会先了解到WCF PreSession模式的一些基本概念。

WCF PreSession模式需要绑定到支持 Session 的 Binding 对象。在客户端代理触发终止操作前,WCF 为每个客户端维持同一个服务对象,因此 PreSession 模式可用来保持调用状态。也正因为如此,PreSession 在大并发服务上使用时要非常小心,避免造成服务器过度负担。虽然支持 Session 的 Binding 对象缺省就会启用 PreSession 模式,但依然建议你强制指定 SessionMode.Required 和 InstanceContextMode.PerSession。

 
 
 
  1. [ServiceContract(SessionModeSessionMode = SessionMode.Required)]  
  2. public interface IMyService  
  3. {  
  4. [OperationContract]  
  5. void Test();  
  6. }  
  7. [ServiceBehavior(InstanceContextModeInstanceContextMode = 
    InstanceContextMode.PerSession)]  
  8. public class MyServie : IMyService, IDisposable  
  9. {  
  10. public MyServie()  
  11. {  
  12. Console.WriteLine("Constructor:{0}", this.GetHashCode());  
  13. }  
  14. [OperationBehavior]  
  15. public void Test()  
  16. {  
  17. Console.WriteLine("Test:{0}", OperationContext.Current.SessionId);  
  18. }  
  19. public void Dispose()  
  20. {  
  21. Console.WriteLine("Dispose");  
  22. }  
  23. }  
  24. public class WcfTest  
  25. {  
  26. public static void Test()  
  27. {  
  28. AppDomain.CreateDomain("Server").DoCallBack(delegate  
  29. {  
  30. ServiceHost host = new ServiceHost(typeof(MyServie), 
    new Uri("http://localhost:8080/MyService"));  
  31. host.AddServiceEndpoint(typeof(IMyService), new WSHttpBinding(), "");  
  32. host.Open();  
  33. });  
  34. //-----------------------  
  35. IMyService channel = ChannelFactory<IMyService>.
    CreateChannel(new WSHttpBinding(),   
  36. new EndpointAddress("http://localhost:8080/MyService"));  
  37. using (channel as IDisposable)  
  38. {  
  39. channel.Test();  
  40. channel.Test();  
  41. }  
  42. }  

WCF PreSession模式代码输出:

 
 
 
  1. Constructor:30136159  
  2. Test:urn:uuid:2f01b61d-40c6-4f1b-a4d6-4f4bc3e8847a  
  3. Test:urn:uuid:2f01b61d-40c6-4f1b-a4d6-4f4bc3e8847a  
  4. Dispose 

以上就是我们为大家介绍的WCF PreSession模式的基本概念。

【编辑推荐】

  1. WCF PreCal模式基本代码示例解析
  2. WCF使用Nhibernate具体操作步骤图解
  3. WCF枚举实现技巧总结
  4. WCF异常处理各种方式详解
  5. WCF方法重载相关实现技巧分享
THE END