轉載網絡代碼.版權歸原作者所有.....
用戶端調用WCF的幾種常用的方式:
1普通調用
var factory = new DataContent.ServiceReference1.CustomerServiceClient();
factory.Open();
List<DataContent.ServiceReference1.Customer> lis = factory.GetAllCustomerList();
factory.Close();
2 異步調用
1 var factory = new DataContent.ServiceReference1.CustomerServiceClient();
IAsyncResult anynRsult = factory.BeginGetAllCustomerList(null, null);
List<DataContent.ServiceReference1.Customer> lis = factory.EndGetAllCustomerList(anynRsult);
factory.Close();
該方法将會阻塞目前線程并等待異步方法的結束,往往不能起到地多線程并發執行應有的作用。我們真正希望的是在異步執行結束後自動回調設定的操作,這樣就可以采用回調的方式來實作這樣的機制了。
在下面的代碼中,我們通過一個匿名方法的形式定義回調操作,由于在回調操用中輸出運算結果時需要使用到參與運算的操作數,我們通過BeginGetAllCustomerList方法的最後一個object類型參數實作向回調操作傳遞資料,在回調操作中通過IAsyncResult對象的AsyncState獲得。
2 var factory = new DataContent.ServiceReference1.CustomerServiceClient();
factory.BeginGetAllCustomerList(delegate(IAsyncResult asyncResult)
{
lis = factory.EndGetAllCustomerList(asyncResult);
factory.Close();
}, null);
3通信工廠
var factory = new ChannelFactory<DataContent.ServiceReference1.ICustomerService>(new BasicHttpBinding(), new EndpointAddress("http://localhost:10625/Service1.svc"));
try
{
var proxy = factory.CreateChannel();
using (proxy as IDisposable)
{
return proxy.GetAllCustomerList();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return new List<DataContent.ServiceReference1.Customer>();
}
finally
{
factory.Close();
}
4 通過事件注冊的方式進行異步服務調用
var factory = new DataContent.ServiceReference1.CustomerServiceClient();
factory.GetAllCustomerListCompleted += (sender, e) =>
{
lis = e.Result;
};
factory.GetAllCustomerListAsync();
factory.Close();
在這裡做個備注:防止下次忘記