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

Ela*_*lad 6 .net c# wcf asynchronous async-await

鉴于此接口

[ServiceContract]
public interface IProductService
{
    [OperationContract]
    Product Get(int id);
}
Run Code Online (Sandbox Code Playgroud)

我想手动(即,不使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

i3a*_*non 9

如果你正在使用ChannelFactoryasync-await你的接口需要返回一个TaskTask<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))
}
Run Code Online (Sandbox Code Playgroud)

  • @Elad是的.`ChannelFactory`本身支持异步.它不会在阻塞操作上创建一个假`Task`. (2认同)