對WCF異步調用進行服務操作
希望我對WCF異步調用的一點經驗能給大家帶來幫助,導致WCF異步的原因也許還有很多,不過在你遇到錯誤時,可以先檢查一下你程序中的字符串,暫時把他們置為””,試試看。沒準就是他引起的問題啊。
我將服務契約的定義單獨形成了一個程序集,并在客戶端直接引用了它。然而,在這樣的服務契約程序集中,是沒有包含異步方法的定義的。因此,我需要修改在客戶端的服務定義,增加操作的異步方法。這無疑為服務契約的重用帶來障礙。至少,我們需要在客戶端維持一份具有異步方法的服務契約。#t#
所幸,在客戶端決定采用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);
- }
注意,在BeginTransferDocument()方法上,必須在OperationContractAttribute中將AsyncPattern屬性值設置為true,因為它的默認值為false。
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);