在MVC操作中调用任务方法但当前线程被锁定

时间:2013-03-22 03:46:25

标签: task deadlock

public class HomeController : Controller
    {   
        public ActionResult Index()
        {
            var t1= Test1().Result;
            return View();
        }

        private async Task<HttpResponseMessage> Test1()
        {
            string strUrl = "http://localhost:52033/api/values";
            var instanceClient = new HttpClient();
            var requestMessage = new HttpRequestMessage(HttpMethod.Get, strUrl);
            var httpRespons = await instanceClient.SendAsync(requestMessage);
            return httpRespons;
        }
    }

当我在名为Test1()的索引操作中时。结果;当前线程死锁程序一直没有响应时会发生,不带结果调用后缀可以正常运行!

1 个答案:

答案 0 :(得分:0)

您不应该在ASP.NET上下文中调用ResultWait;一个原因是它可能导致死锁,as I explain on my blog

相反,您应该使用await,如下所示:

public async Task<ActionResult> Index()
{
    var t1 = await Test1();
    return View();
}