加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:24:44 所属栏目:百科 来源:网络整理
导读:鉴于此接口 [ServiceContract]public interface IProductService{ [OperationContract] Product Get(int id);} 我想手动(即,不使用VS中的scvutil或Add Service Reference)创建客户端代理. 我是用以下方式做的 public class ProductService: IProductService{
鉴于此接口
[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))
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读