I am trying to call an async method from a synchronous library method and running in to problems. I'll start by showing some code.
public void Execute(RegisterUserCommand command)
{
var user = new UserAccountEntity
{
UserName = command.EmailAddress,
Email = command.EmailAddress,
};
var task = _userManager.CreateAsync(user, command.Password);
var result = task.Result; // Causes deadlock
if (!result.Succeeded)
throw new CommandInvalidException("Command failed", result.Errors);
}
Calling task.Result is making my code deadlock.
After doing some research (including reading this) and some digging I now think I have a relatively good understanding of what causes the deadlock.
I am using the UserManager from asp .net Identity. I used dotPeek and found out that UserManager.CreateAsync calls UserValidator.ValidateAsync which will await some tasks without calling .ConfigureAwait(false).
- Am I correct that this will cause task.Result to deadlock? How can I solve this deadlock when I have no control over the async method being called?
- Is it ever possible to call .Result on a task returned from a library method that does not implement ConfigureAwait(false)?
- The answer here says to "explicitly execute your async method in a thread pool thread and wait for it to finish". I will test this later today, but does this mean there is no way to fix my problem without me manually starting a new thread?
- I think that the best solution to the problem would be to make my Execute method async, is this assumption correct? I'd rather wait with this solution though and try to fix it without using async first.