thd
thd

Reputation: 2083

Execution hangs when MVC client but works when client is console app or test project

I have a MVC5 project that is using a service and repository in a class library project. When I run/debug the following code as a MVC project, the execution hangs at "return await client.GetAsync(url);" in the repository. No exception is thrown.

If I call the same service code and repository code from a unit test or console application, then the code works fine.

What is wrong with the code or what am I doing wrong?

//File: TestController.cs

public ActionResult Index(string q)
{
    //Code

    var mySvc = new MyService();
    var svcResponse = mySvc.GetAsync(q).Result;

    //More code
}

//File: MyService.cs

public async Task<MyResponse> GetAsync(string q)
{
    var myRepo = new MyRepository();
    var response = await myRepo.GetAsync(q);
    var json = await response.Content.ReadAsStringAsync();
    return JsonConvert.DeserializeObject<MyResponse>(json);
}

//File: MyRepository.cs

public async Task<HttpResponseMessage> GetAsync(string q)
{
    var url = URL_CONSTANT + q;
    using (var client = new HttpClient())
    {
        return await client.GetAsync(url);   //Execution hangs here when MVC!
    }
}

Upvotes: 1

Views: 194

Answers (1)

shurik
shurik

Reputation: 805

You should make your controller method async instead of blocking on .Result (which causes a deadlock). Your controller action should be something like this

   public async Task<IActionResult> Index(string q)
    {
        //Code

        var mySvc = new MyService();
        var svcResponse = await mySvc.GetAsync(q);

        //More code
    }

See for example here for more details http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

Upvotes: 7

Related Questions