WCF異步調用在客戶端中執行方法介紹
WCF異步調用,這樣的一種技術,對于一個經驗不太豐富的編程人員來說,可能還不是很好掌握這一方法的應用。在這里就為大家介紹一下WCF異步調用在客戶端中執行方法。#t#
因為我將服務契約的定義單獨形成了一個程序集,并在客戶端直接引用了它。然而,在這樣的服務契約程序集中,是沒有包含異步方法的定義的。因此,我需要修改在客戶端的服務定義,增加操作的異步方法。這無疑為服務契約的重用帶來障礙。至少,我們需要在客戶端維持一份具有WCF異步調用方法的服務契約。
所幸,在客戶端決定采用WCF異步調用我所設計的服務操作時,雖然需要修改客戶端的服務契約接口,但并不會影響服務端的契約定義。因此,服務端的契約定義可以保持不變,而在客戶端則修改接口定義如下:
- [ServiceContract]
- public interface IDocuments
ExplorerService- {
- [OperationContract]
- Stream TransferDocument
(Document document);- [OperationContract
(AsyncPattern = true)]- IAsyncResult BeginTransfer
Document(Document document,- AsyncCallback callback,
object asyncState);- Stream EndTransferDocument
(IAsyncResult result);- }
注意,在BeginTransferDocument()方法上,必須在OperationContractAttribute中將AsyncPattern屬性值設置為true,因為它的默認值為false。合理地利用服務的WCF異步調用,可以有效地提高系統性能,合理分配任務的執行。特別對于UI應用程序而言,可以提高UI的響應速度,改善用戶體驗。在我編寫的應用程序中,下載的文件如果很大,就有必要采用異步方式。WCF異步調用方式如下:
- BasicHttpBinding
- binding = new BasicHttpBinding();
- binding.SendTimeout = TimeSpan.
FromMinutes(10);- binding.TransferMode = Transfe
rMode.Streamed;- binding.MaxReceivedMessageSize =
9223372036854775807;- EndpointAddress address =
new EndpointAddress (http://l
ocalhost: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);
以上就是WCF異步調用的相關使用方法。