WCF PreSession模式保持調(diào)用狀態(tài)
WCF開(kāi)發(fā)工具是.NET Framework 3.5的一個(gè)重要組成部件。它的出現(xiàn)在一定程度上改變了開(kāi)發(fā)人員的編程習(xí)慣,為開(kāi)發(fā)人員帶來(lái)了非常大幫助。在這里我們將會(huì)先了解到WCF PreSession模式的一些基本概念。
WCF PreSession模式需要綁定到支持 Session 的 Binding 對(duì)象。在客戶端代理觸發(fā)終止操作前,WCF 為每個(gè)客戶端維持同一個(gè)服務(wù)對(duì)象,因此 PreSession 模式可用來(lái)保持調(diào)用狀態(tài)。也正因?yàn)槿绱?,PreSession 在大并發(fā)服務(wù)上使用時(shí)要非常小心,避免造成服務(wù)器過(guò)度負(fù)擔(dān)。雖然支持 Session 的 Binding 對(duì)象缺省就會(huì)啟用 PreSession 模式,但依然建議你強(qiáng)制指定 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
以上就是我們?yōu)榇蠹医榻B的WCF PreSession模式的基本概念。
【編輯推薦】