[英]ASP.NET MVC 5 and WCF async troubles
Our application uses WCF as data provider and on some pages we have a multiple calls to different services. 我们的应用程序使用WCF作为数据提供者,在某些页面上,我们多次调用不同的服务。 Good piece to optimize I thought, and started to rewrite it to the async
. 我认为是优化的好作品,并开始将其重写为async
。 So before the rewrite it looks like 所以在重写之前
public ActionResult SomeAction(int id)
{
var r1 = AService.Call1();
var r2 = BService.Call2();
var r3 = CService.Call3();
//another logic
}
and now it turned to 现在变成了
public async Task<ActionResult> SomeAction(int id)
{
var r1 = await AService.Call1Async();
var r2 = await BService.Call2Async();
var r3 = await CService.Call3Async();
//another logic
}
With this approach I faced two problems: 通过这种方法,我面临两个问题:
Update: @zuckerberg answer helps with optimization (I'm creating tasks and putting them in awaitable Task.WhenAll()
), but I'm still getting hangs on WCF services — while synchronous calls going correctly, asynchronous calls turning calling logic to sleep and never awakes it back. 更新: @zuckerberg答案有助于优化(我正在创建任务并将其放入等待的Task.WhenAll()
),但我仍然挂在WCF服务上—同步调用正常进行,异步调用使调用逻辑进入睡眠状态永不唤醒。
with async/await they run asynchronously. 与异步/等待它们异步运行。 Which means they don't wait for each other or the main thread. 这意味着他们不等待对方或主线程。 If there are dependancies or you need to wait for all 3 to finish first before returning a result, then I suggest using something like: 如果存在依赖关系,或者您需要先等待所有3个对象完成才能返回结果,则建议使用类似以下内容的方法:
var r1 = await AService.Call1Async();
var r2 = await BService.Call2Async();
var r3 = await CService.Call3Async();
await Task.WhenAll(r1, r2, r3);
//more logic
Hope this helps nudge you in the right direction. 希望这可以帮助您朝正确的方向前进。 However, without seeing more code, I can't tell if by just async/await'ing your calls will actually improve performance or not (it's not always a performance booster) and your time/effort might be better spent elsewhere. 但是,在没有看到更多代码的情况下,我无法确定仅通过异步/等待来改善您的呼叫是否会真正提高性能(这并不总是提高性能),并且您的时间/精力可能会花在其他地方。
Good luck! 祝好运!
1.Starting functions with inner async calls from constructor of static class is a bad idea, but SomeMethodAsync().Result
helps — of course there's no benefit for controller, but in that little case it acceptable. 1.使用静态类的构造函数的内部异步调用来启动函数不是一个好主意,但SomeMethodAsync().Result
帮助-控制器当然没有任何好处,但是在那种情况下,它是可以接受的。
2.Yes, I misunderstood async/await
, so I rewrite code to something like this: 2.是的,我误解了async/await
,所以我将代码重写为如下形式:
var get1Task = AService.Call1Async();
var get2Task = BService.Call2Async();
var get3Task = CService.Call3Async();
await Task.WhenAll(get1Task, get2Task, get3Task);
var r1 = get1Task.Result;
var r2 = get2Task.Result;
var r3 = get3Task.Result;
//more logic
It gave me a good speedup on pages with lot of WCF calls and I'm kinda happy. 这使我在使用许多WCF调用的页面上获得了很好的加速效果,我感到很高兴。
My thanks going to @zuckerberg for pointing to the right direction. 感谢@zuckerberg指出正确的方向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.