Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
696 views
in Technique[技术] by (71.8m points)

c# - Using await Task<T> async hangs controller in MVC app

I have two MVC websites. Site 1 has a controller that calls Site 2 with the following code

 //  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;
    }
}

I'm able to directly browse the URL and see the JSON.. but what is the correct way to download JSON from my peer website in MVC?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should probably turn the controller method into an async method and use await to avoid deadlocks.

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

Microsoft's ASP.NET tutorial includes a page on async methods in ASP.NET MVC 4.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...