客户端调用 WCF 的几种方式
转载网络代码.版权归原作者所有.....
客户端调用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();
在这里做个备注:防止下次忘记