在WebApi方法中调用异步方法

and*_*cek 2 c# async-await asp.net-web-api

我有两个方法,一个在WebApi(Post()),一个在我的数据仓库(Save()).在Save方法中,我用await调用异步方法.Save方法本身是异步的.

我最终想要完成的是在Save方法中的函数完成后向用户发送201.

Web api:

public HttpResponseMessage Post(JObject input)
{
    Event postedEvent = new Event(// here be data //);
    IEventRepo repo = new MongoDBRepo();

    return repo.Save(postedEvent).Result;
}
Run Code Online (Sandbox Code Playgroud)

数据回购:

public async Task<HttpResponseMessage> Save(Event e)
{
    await _collection.InsertOneAsync(e);

    return new HttpResponseMessage(HttpStatusCode.Created);
}
Run Code Online (Sandbox Code Playgroud)

现在发生的是Save将完成,但HttpResponseMessage永远不会被发送.因此对服务器的请求将挂起.

Ant*_*t P 7

你有一个死锁,因为你阻止了Task返回的结果repo.Save而不是等待它.

您需要一直使用async控制器操作:

public async Task<HttpResponseMessage> Post(JObject input)
{
    Event postedEvent = new Event(/* here be data */);
    IEventRepo repo = new MongoDBRepo();

    return await repo.Save(postedEvent);
}
Run Code Online (Sandbox Code Playgroud)

有关此死锁原因的更详细说明,请参阅此优秀博客文章,但实际上,这是由于repo中异步调用的延续正在等待已被方法阻止的请求上下文这一事实引起的.你正在调用回购(后者正在等待继续完成等等......).

  • 谢谢.就是这样!我是异步编程的新手,请原谅我愚蠢的问题:) (2认同)