c# – 为手动生成的WCF(客户端)代理实现异步/等待模式

前端之家收集整理的这篇文章主要介绍了c# – 为手动生成的WCF(客户端)代理实现异步/等待模式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
鉴于此接口
  1. [ServiceContract]
  2. public interface IProductService
  3. {
  4. [OperationContract]
  5. Product Get(int id);
  6. }

我想手动(即,不使用VS中的scvutil或Add Service Reference)创建客户端代理.

我是用以下方式做的

  1. public class ProductService: IProductService
  2. {
  3. readonly ChannelFactory<IProductService> factory;
  4.  
  5. public ProductService()
  6. {
  7. factory = new ChannelFactory<IProductService>("*");
  8. }
  9.  
  10. public Product Get(int id)
  11. {
  12. var channel = factory.CreateChannel();
  13. return channel.Get(id);
  14. }
  15. }

我的问题是我也想要这种方法的async / await版本,只在客户端,服务器端仍然是同步的.

我希望这是一个通用的解决方案,因为我有很多这种方法和服务.

解决方法

如果您使用ChannelFactory来允许async-await,则您的接口需要返回任务或任务< T>.

它会强制你的服务器端同时返回一个任务但你可以与Task.CompletedTask和Task.FromResult同步执行,如果你坚持让它保持同步(不过为什么你有选择).

例如:

  1. [ServiceContract]
  2. interface IProductService
  3. {
  4. [OperationContract]
  5. Task<Product> GetAsync(int id);
  6. }
  7.  
  8. class ProductService : IProductService
  9. {
  10. ChannelFactory<IProductService> factory;
  11.  
  12. public ProductService()
  13. {
  14. factory = new ChannelFactory<IProductService>("*");
  15. }
  16.  
  17. public Task<Product> GetAsync(int id)
  18. {
  19. var channel = factory.CreateChannel();
  20. return channel.GetAsync(id);
  21. }
  22. }
  23.  
  24. class ProductAPI : IProductService
  25. {
  26. public Task<Product> GetAsync(int id) => Task.FromResult(Get(id))
  27. }

猜你在找的C#相关文章