鉴于此接口
- [ServiceContract]
- public interface IProductService
- {
- [OperationContract]
- Product Get(int id);
- }
我想手动(即,不使用VS中的scvutil或Add Service Reference)创建客户端代理.
我是用以下方式做的
- public class ProductService: IProductService
- {
- readonly ChannelFactory<IProductService> factory;
- public ProductService()
- {
- factory = new ChannelFactory<IProductService>("*");
- }
- public Product Get(int id)
- {
- var channel = factory.CreateChannel();
- return channel.Get(id);
- }
- }
我的问题是我也想要这种方法的async / await版本,只在客户端,服务器端仍然是同步的.
解决方法
如果您使用ChannelFactory来允许async-await,则您的接口需要返回任务或任务< T>.
它会强制你的服务器端同时返回一个任务但你可以与Task.CompletedTask和Task.FromResult同步执行,如果你坚持让它保持同步(不过为什么你有选择).
例如:
- [ServiceContract]
- interface IProductService
- {
- [OperationContract]
- Task<Product> GetAsync(int id);
- }
- class ProductService : IProductService
- {
- ChannelFactory<IProductService> factory;
- public ProductService()
- {
- factory = new ChannelFactory<IProductService>("*");
- }
- public Task<Product> GetAsync(int id)
- {
- var channel = factory.CreateChannel();
- return channel.GetAsync(id);
- }
- }
- class ProductAPI : IProductService
- {
- public Task<Product> GetAsync(int id) => Task.FromResult(Get(id))
- }