WCF ChannelFactory异步调用

Krz*_*iek 7 wcf asynchronous task channelfactory task-parallel-library

我正在使用WCF和TPL异步库,我需要的是能够请求多个WCF方法并等待所有步骤都完成,到目前为止,我发现.NET 4.5中有非常方便的方法Task.Factory.ContinueWhenAll可以用于等待所有通话结束

我发现了以下几种以异步方式请求WCF调用的方法
。通过使用由“添加引用”对话框生成的代理以及选项“生成基于任务的操作”-> [例如,此处] [1]-在我的情况下不是一个选项就像我们使用Raw ChannelFactory
Option 2一样。通过将同步调用包装在任务中,例如

    ChannelFactory<IService1> factory = new ChannelFactory<IService1>("BasicHttpBinding_IService1");  

        Task<string> t1 = Task<string>.Factory.StartNew(() => { return factory.CreateChannel().GetData(2); });
        Task<string> t2 = Task<string>.Factory.StartNew(() => { return factory.CreateChannel().GetData(5); });

        Task.Factory.ContinueWhenAll(new[] { t1, t2 }, t =>
        {
            foreach (var task in t)
            {
                //get result here
            }
        });
Run Code Online (Sandbox Code Playgroud)

选项3.通过创建客户端异步版本的契约接口,例如

[ServiceContract(Namespace = "X", Name = "TheContract")]//Server side contract
public interface IService1
{
    [OperationContract]
    string GetData(int value);
}

[ServiceContract(Namespace = "X", Name = "TheContract")]//client side contract
public interface IService1Async
{
    [OperationContract]
    string GetData(int value);

    [OperationContract]
    Task<string> GetDataAsync(int value);
}
Run Code Online (Sandbox Code Playgroud)

有了这个,我可以异步调用方法,例如

 ChannelFactory<IService1Async> factory = new ChannelFactory<IService1Async>("BasicHttpBinding_IService2");

        var t1 = factory.CreateChannel().GetDataAsync(2);
        var t2 = factory.CreateChannel().GetDataAsync(5);

        Task.Factory.ContinueWhenAll(new[] { t1, t2 }, (Task<string>[] t) =>
            {
                foreach (var task in t)
                {
                    //get result here
                }
            });
Run Code Online (Sandbox Code Playgroud)

因此问题如下:与选项2相比,选项3有什么优势?像选项2中那样调用WCF方法是否正确?与3相比,选项2具有一个优点,即无需创建客户端合同接口。

svi*_*ick 4

在选项 #2 中,每次调用GetData()都会在方法执行的整个过程中阻塞一个线程。在选项 #3 中,当GetDataAsync()操作正在进行时,不会阻塞任何线程。

这意味着选项 #3 更有效,-Async如果效率对您很重要,您应该使用该方法的版本。