在不使用 await 的情况下调用异步方法时防止死锁 [英] Preventing a deadlock when calling an async method without using await

查看:51
本文介绍了在不使用 await 的情况下调用异步方法时防止死锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要调用一个从内部返回Task的方法

I need to call a method returning a Task from within

public override void OnActionExecuting(ActionExecutingContext filterContext)

它不会让我使这个方法异步它会抛出以下内容

It wont let me make this method async it throws the following

异步模块或处理程序完成,而异步模块或处理程序已完成操作仍在等待中.

An asynchronous module or handler completed while an asynchronous operation was still pending.

和调用时

 entityStorage.GetCurrentUser().Result

我陷入僵局.我怎样才能避免这种情况?

I get a deadlock. How can I avoid this?

我一直在玩弄它,想出了像

I have been playing around with it coming up with stuff like

entityStorage.GetCurrentUser().Result.ConfigureAwait(false).GetAwaiter().GetResult();

但这不起作用.我该怎么做?我的解决方案需要使用 ASP.NET 4 和 Async Targetting Pack,我无法在部署到 Azure 时使用 ASP.NET 4.5.

But this isn't working. How can I do it? My solution will need to work with ASP.NET 4 and the Async Targetting Pack, I can't use ASP.NET 4.5 as am deploying to Azure.

推荐答案

由于 await 只是编译器为您重写延续的语法糖,因此最直接"的路径是采用任何代码将跟随您的 await并将其设为 ContinueWith 调用.

Since await is just syntax sugar for the compiler rewriting a continuation for you, the most 'direct' path would be to take whatever code was going to follow your await and make it a ContinueWith call.

所以,例如:

entityStorage.GetCurrentUser().ContinueWith(t =>
{
    // do your other stuff here
});

这篇关于在不使用 await 的情况下调用异步方法时防止死锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆