同时等待具有独立延续的多个 WCF 异步调用

Concurrently awaiting multiple WCF asynchronous calls with independent continuations

我有一个场景,我需要调用多个 WCF 异步调用,这些调用可以彼此独立进行,每个调用都有自己的延续来更新 UI。

假设我有这样的函数:

private Task<bool> ExecuteSomeWorkAsync(int delay)
 {
     int _delay = delay;
     var t = Task<bool>.Factory.StartNew(
         () =>
         {
             Thread.Sleep(_delay);

             return true;
         });

     return t;
 }

如果我创建一个进行多次调用的本地 WPF 应用程序,每个调用的时间可能会有所不同 return 结果,它会按预期工作。 在示例中,第二个任务在第一个任务之前完成,绑定到第二个 属性 的 UI 元素在第一个任务之前更新。

 TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
                    await Task.WhenAll(
                        ExecuteSomeWorkAsync(2000).ContinueWith(task1 => { SomePropertyBoundToUIElement1 = task1.Result; }, uiScheduler),
                        ExecuteSomeWorkAsync(1000).ContinueWith(task2 => { SomePropertyBoundToUIElement2 = task2.Result; }, uiScheduler)
                        );

但是,如果我尝试在通过客户端代理调用 ExecuteSomeWorkAsync 的 WCF 中实现此功能,则 UI 仅在最慢的 任务完成。

那么,有没有办法在 WCF 中完成这项工作?

为了回答我自己的问题,有一种方法可以使该示例在 WCF 中运行。 解决方案是指定适当的 ConcurrencyMode 选项。

通过使用此服务行为装饰 WCF 服务,我获得了我想要的并行性。

 [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]

显然 WCF 默认是 Single ConcurrencyMode,因此服务按顺序解析请求。