zoukankan      html  css  js  c++  java
  • 客户端调用 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();

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

  • 相关阅读:
    C字符串和C++中string的区别 &amp;&amp;&amp;&amp;C++中int型与string型互相转换
    UML的类图关系分为: 关联、聚合/组合、依赖、泛化(继承)
    STL map详细用法和make_pair函数
    字符串旋转(str.find()---KMP)
    层次遍历二叉树
    图像特征提取三大法宝:HOG特征,LBP特征,Haar特征
    位运算---整数间的转化
    最大公倍数
    单链表的实现
    jsp下Kindeditor环境搭建
  • 原文地址:https://www.cnblogs.com/w2011/p/3181946.html
Copyright © 2011-2022 走看看