WCF开发工具是.NET Framework 3.5的一个重要组成部件。它的出现在一定程度上改变了开发人员的编程习惯,为开发人员带来了非常大帮助。在这里我们将会先了解到WCF PreSession模式的一些基本概念。
WCF PreSession模式需要绑定到支持 Session 的 Binding 对象。在客户端代理触发终止操作前,WCF 为每个客户端维持同一个服务对象,因此 PreSession 模式可用来保持调用状态。也正因为如此,PreSession 在大并发服务上使用时要非常小心,避免造成服务器过度负担。虽然支持 Session 的 Binding 对象缺省就会启用 PreSession 模式,但依然建议你强制指定 SessionMode.Required 和 InstanceContextMode.PerSession。
- [ServiceContract(SessionModeSessionMode = SessionMode.Required)]
- public interface IMyService
- {
- [OperationContract]
- void Test();
- }
- [ServiceBehavior(InstanceContextModeInstanceContextMode =
InstanceContextMode.PerSession)]- public class MyServie : IMyService, IDisposable
- {
- public MyServie()
- {
- Console.WriteLine("Constructor:{0}", this.GetHashCode());
- }
- [OperationBehavior]
- public void Test()
- {
- Console.WriteLine("Test:{0}", OperationContext.Current.SessionId);
- }
- public void Dispose()
- {
- Console.WriteLine("Dispose");
- }
- }
- public class WcfTest
- {
- public static void Test()
- {
- AppDomain.CreateDomain("Server").DoCallBack(delegate
- {
- ServiceHost host = new ServiceHost(typeof(MyServie),
new Uri("http://localhost:8080/MyService"));- host.AddServiceEndpoint(typeof(IMyService), new WSHttpBinding(), "");
- host.Open();
- });
- //-----------------------
- IMyService channel = ChannelFactory<IMyService>.
CreateChannel(new WSHttpBinding(),- new EndpointAddress("http://localhost:8080/MyService"));
- using (channel as IDisposable)
- {
- channel.Test();
- channel.Test();
- }
- }
- }
WCF PreSession模式代码输出:
- Constructor:30136159
- Test:urn:uuid:2f01b61d-40c6-4f1b-a4d6-4f4bc3e8847a
- Test:urn:uuid:2f01b61d-40c6-4f1b-a4d6-4f4bc3e8847a
- Dispose
以上就是我们为大家介绍的WCF PreSession模式的基本概念。
【编辑推荐】