分析客戶端執行WCF異步調用
剛剛做完一個WCF的一個項目,把我我的一點經驗傳授給大家一點,我們今天先來看看WCF異步調用,客戶端究竟應該如何執行WCF異步調用呢?如果采用編程方式獲得服務代理對象,這一問題會變得比較糟糕。因為我將服務契約的定義單獨形成了一個程序集,并在客戶端直接引用了它。然而,在這樣的服務契約程序集中,是沒有包含異步方法的定義的。因此,我需要修改在客戶端的服務定義,增加操作的異步方法。這無疑為服務契約的重用帶來障礙。至少,我們需要在客戶端維持一份具有異步方法的服務契約。
所幸,在客戶端決定采用異步方式調用我所設計的服務操作時,雖然需要修改客戶端的服務契約接口,但并不會影響服務端的契約定義。因此,服務端的契約定義可以保持不變,而在客戶端則修改接口定義如下:
- [ServiceContract]
- public interface IDocumentsExplorerService
- {
- [OperationContract]
- Stream TransferDocument(Document document);
- [OperationContract(AsyncPattern = true)]
- IAsyncResult BeginTransferDocument(Document document,
- AsyncCallback callback, object asyncState);
- Stream EndTransferDocument(IAsyncResult result);
- }
#T#注意,在BeginTransferDocument()方法上,必須在OperationContractAttribute中將AsyncPattern屬性值設置為true,因為它的默認值為false。合理地利用服務的異步調用,可以有效地提高系統性能,合理分配任務的執行。特別對于UI應用程序而言,可以提高UI的響應速度,改善用戶體驗。在我編寫的應用程序中,下載的文件如果很大,就有必要采用異步方式。WCF異步調用方式如下:
- BasicHttpBinding binding = new BasicHttpBinding();
- binding.SendTimeout = TimeSpan.FromMinutes(10);
- binding.TransferMode = TransferMode.Streamed;
- binding.MaxReceivedMessageSize = 9223372036854775807;
- EndpointAddress address = new EndpointAddress
- ("http://localhost:8008/DocumentExplorerService");
- ChannelFactory factory =
- new ChannelFactory(binding,address);
- m_service = factory.CreateChannel();
- ……
- IAsyncResult result = m_service.BeginTransferDocument(doc,null,null);
- result.AsyncWaitHandle.WaitOne();
- Stream stream = m_service.EndTransferDocument(result);