FindAsync never comes back however Find works just fine

376 Views Asked by At

I am using FluentValidation to validate the objects. I am simply checking checking whether the user exists in database or not. In my case, DbContext.Entity.Find works just fine but DbContext.Entity.FindAsync never returns.

Please refer to the below source code where it is happening.

    public class ChangeStatusOfUserCommandValidator : AbstractValidator<ChangeStatusOfUserCommand>
{
    private readonly FieldSellDbContext dbContext;
    private ChangeStatusOfUserCommandValidator()
    { }

    public ChangeStatusOfUserCommandValidator(FieldSellDbContext databaseContext)
    {
        dbContext = databaseContext;
        RuleFor(u => u.UserId).NotEmpty();
        RuleFor(u => u.UserId).MustAsync(UserExists).WithMessage("Provided user id already exists in the database.");
    }

    public async Task<bool> UserExists(int value, CancellationToken cancellationToken)
    {
        var user = await dbContext.Users.FindAsync(value, cancellationToken);
        //var user = dbContext.Users.Find(value); --Works fine even in async method
        return user != null;
    }
}

Thanks

1

There are 1 best solutions below

2
Stephen Cleary On

Your problem is almost certainly further up your call stack, where the code is calling Task<T>.Result, Task.Wait(), Task.GetAwaiter().GetResult(), or some similar blocking method. If your code blocks on asynchronous code in a single-threaded context (e.g., on a UI thread), it can deadlock.

The proper solution is to use async all the way; that is, use await instead of blocking on asynchronous code. Fluent validation has an asynchronous workflow (e.g., ValidateAsync, MustAsync), so you'll need to be sure to use that rather than the synchronous APIs.