【问题标题】:Using await Task<T> async hangs controller in MVC app在 MVC 应用程序中使用 await Task<T> 异步挂起控制器
【发布时间】:2013-11-26 20:33:52
【问题描述】:

我有两个 MVC 网站。站点 1 有一个控制器,它使用以下代码调用站点 2

 //  If I remove this in the controller of site1, then execution continues....
 var asdf =   SharedTypes.Utilities.GetjsonStream("http://localhost:11541/UIDP/Details/a1?format=json");
 string g =  asdf.Result;


public class Utilities
{
    public static async Task<string> GetjsonStream(string url)
    {
        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync(url);
        string content = await response.Content.ReadAsStringAsync();
        Debug.WriteLine("Content: " + content);
        return content;
    }
}

我可以直接浏览 URL 并查看 JSON.. 但是在 MVC 中从我的对等网站下载 JSON 的正确方法是什么?

【问题讨论】:

    标签: c# asp.net-mvc json asp.net-mvc-4 asynchronous


    【解决方案1】:

    您可能应该将控制器方法转换为async 方法并使用awaitavoid deadlocks

    public async Task<ActionResult> MyActionAsync()
    {
        var asdf = SharedTypes.Utilities.GetjsonStream(someUrl);
        string g = await asdf;
        // return something
    }
    

    Microsoft 的 ASP.NET 教程包括一个关于 async methods in ASP.NET MVC 4 的页面。

    【讨论】:

    • 这似乎适用于一个项目调用另一个项目......但我无法让它为 MVC 应用程序使用 HTTPWebRequest 调用自身。无论如何,这可能是不必要的开销。这对于两个站点之间的通信非常有用...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-11
    • 2015-10-13
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多