WCF PreSession模式保持調用狀態
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模式的基本概念。
【編輯推薦】