客户端调用 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(nullnull);             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();

 

在这里做个备注:防止下次忘记

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值