【问题标题】:Async method called to the web api with async is stuck and not returning to the caller使用 async 调用 web api 的异步方法被卡住并且没有返回给调用者
【发布时间】:2019-08-29 18:29:04
【问题描述】:

我想通过 C# Task 调用 Web API,但我无法获得返回的结果,尽管它确实会跳转到我指出的 URL 以获取值。

我是否错误地实现了 async 和 await 方法?

下面是我的代码:

  • 路由前缀为:

    的Web API
    [RoutePrefix("api/values")]
    
  • Web API 内部的方法如下:

    [Route("Developer")]
    [HttpGet]
    public Task<List<string>> Developer()
    {
        var developer = new List<string> { "Developer", "Developer" };
    
        return Task.FromResult(developer);
    }
    
  • 控制器

    private async Task<List<string>> Developer()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:52717/");
    
            var response = await client.GetAsync("api/values/Developer");
    
            if (response.IsSuccessStatusCode)
                return new List<string>();
    
            throw new Exception("Unable to get the values");
        }
    }
    
    public ActionResult Index()
    {
        Task.WaitAll(Developer());
    
        return View();
    }
    

每当我启动浏览器时,它都会进入 Index(),然后进入 Developer(),但是,它一直卡住并一直加载,直到 var response = await client.GetAsync("api/values/Developer") 被调用并一直运行到return Task.FromResult(developer);,一直卡在加载中。

有人知道如何让 Web API 回到调用者那里吗?

任何帮助将不胜感激。

谢谢

【问题讨论】:

  • 如果不是设置基地址而是对整个 url 执行 getasync,您会看到不同的行为吗?
  • 嗨@BugFinder,我已经尝试将整个URL放入GetAsync方法和Uri方法中,但没有任何区别。
  • 是的,您错误地使用了asyncTask.WaitAll 阻塞了您的请求线程。

标签: c# multithreading asp.net-web-api


【解决方案1】:

不要阻塞async代码;使用async all the way:

public async Task<ActionResult> Index()
{
  await Developer();

  return View();
}

【讨论】:

  • 您好,已经尝试过您的解决方案,它按预期工作。感谢您的帮助。
猜你喜欢
  • 2019-08-28
  • 1970-01-01
  • 2019-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-19
  • 1970-01-01
  • 2015-05-12
相关资源
最近更新 更多