Reputation: 53
I have two methods, one in WebApi (Post()) and one in my data repo (Save()). Inside the Save method I call an async method with await. The Save method itself is async.
What I in the end want to accomplish is that after the function in the Save method completes to send 201 to the user.
Web api:
public HttpResponseMessage Post(JObject input)
{
Event postedEvent = new Event(// here be data //);
IEventRepo repo = new MongoDBRepo();
return repo.Save(postedEvent).Result;
}
Data repo:
public async Task<HttpResponseMessage> Save(Event e)
{
await _collection.InsertOneAsync(e);
return new HttpResponseMessage(HttpStatusCode.Created);
}
What happens now is that the Save will be done, but the HttpResponseMessage will never get sent. So the request to the server will hang.
Upvotes: 2
Views: 8051
Reputation: 25231
You have a deadlock because you are blocking on the result of the Task
returned by repo.Save
instead of awaiting it.
You need to use async
all the way up to your controller action:
public async Task<HttpResponseMessage> Post(JObject input)
{
Event postedEvent = new Event(/* here be data */);
IEventRepo repo = new MongoDBRepo();
return await repo.Save(postedEvent);
}
See this excellent blog post for a more detailed explanation of the cause of this deadlock but - in essence - it is caused by the fact that the continuation for the asynchronous call in the repo is waiting on the request context that is already blocked by the method you're calling the repo from (which in turn is waiting for the continuation to complete and so on...).
Upvotes: 8