【问题标题】:How to implement an async wcf client for a synchronous service如何为同步服务实现异步 wcf 客户端
【发布时间】:2013-01-14 17:46:58
【问题描述】:

有没有一种方法可以在不添加服务引用的情况下为同步 WCF 服务创建异步客户端?这是针对 .NET 4 客户端的。

【问题讨论】:

    标签: wcf asynchronous


    【解决方案1】:

    Visual Studio 中的服务引用只不过是一个代码生成器,它创建一个代理类,其中包含调用 Web 服务所需的相应数据元素。当然,如果您真的想完成繁琐无聊的工作,您可以手动构建代理。

    也许从使用 .net 反射器反编译 System.ServiceModel.ClientBase 开始?

    对ChannelFactory做一些研究:http://msdn.microsoft.com/en-us/library/system.servicemodel.channelfactory.aspx

    即使通过包装 ChannelFactory 实现我自己的客户端,我仍然在另一个项目中使用 Add Service 引用来创建类定义并将它们移动到实际项目中。这是一个很好的妥协。

    这是一个简单的异步服务接口:

    [ServiceContract(Name = "IService")]
    public interface IServiceAsync
    {
        [OperationContract(AsyncPattern = true)]
        IAsyncResult BeginGetStuff(string someData, AsyncCallback callback, object state);
    
        IEnumerable<Stuff> EndGetStuff(IAsyncResult result);
    }
    

    .NET 合约可能如下所示:

    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        IEnumerable<Stuff> GetStuff(string someData);
    }
    

    然后在代码中,假设您使用 HTTP,无安全性和二进制消息编码,类似这样(抱歉,我没有编译任何这些,只是使用我为项目编写的一些代码键入它):

    //Create a binding for the proxy to use
    HttpTransportBindingElement httpTransportBindingElement;
    
    httpTransportBindingElement = new HttpTransportBindingElement();
    absoluteServiceUri = new Uri(absoluteServiceUri.OriginalString + BinaryEndpointUri, UriKind.Absolute);
    }
    
    //Create the message encoding binding element - we'll specify binary encoding
    var binaryMessageEncoding = new BinaryMessageEncodingBindingElement();
    
    //Add the binding elements into a Custom Binding            
    var customBinding = new CustomBinding(binaryMessageEncoding, httpTransportBindingElement);
    
    // Set send timeout
    customBinding.SendTimeout = this.SendTimeout;   
    
    var factory = new ChannelFactory<IServiceAsync>(customBinding, new EndpointAddress(absoluteServiceUri, new AddressHeader[0]));
    
    var channel = factory.CreateChannel();
    channel.BeginGetStuff(Bla, results => { // Do something }, null);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-03
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 2010-12-25
      • 2014-11-09
      • 1970-01-01
      相关资源
      最近更新 更多