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();

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

  • 相关阅读:
    Zero-shot Relation Classification as Textual Entailment (Abiola Obamuyide, Andreas Vlachos, 2018)阅读笔记:Model
    高阶Erlang:超大只的问答房间
    高阶的Parser:可变运算优先级
    Erlang练习2:火烈鸟
    Erlang实现的模拟kaboose(山寨kahoot)
    Prolog模拟社交圈
    08-bootcss
    07-jQuery
    06-字符串、表单form、input标签
    05-有名/无名函数
  • 原文地址:https://www.cnblogs.com/w2011/p/3181946.html
Copyright © 2011-2022 走看看