0

How to check both id && username in the same time in this user variable to pass it in CheckPasswordSignInAsync method as first paramter and thanks

        var user = await _userManager.FindByNameAsync(userForLoginDto.UserName);
                    await _userManager.FindByIdAsync(userForLoginDto.Id);

1 Answers1

2

Pass tasks that you want to run in parallel to Task.WhenAny and then get result of first completed task:

var completedTask = await Task.WhenAny(
     FindByNameAsync(userForLoginDto.UserName),
     FindbyIdAsync(userForLoginDto.Id));
var user = await completedTask;

Note: usually you should not run a parallel search for the same data in the same database. Search by primary key should be fastest.

If you want to check whether user name is taken by another user, then just search by user name and check id of the returned user if any.

Update: If those searches are independent and you just want to run them in parallel and get all results, then use Task.WhenAll - it will return array or resuls when all tasks are completed:

var users = await Task.WhenAll(
     FindByNameAsync(userForLoginDto.UserName),
     FindbyIdAsync(userForLoginDto.Id));
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • What will occur if the first search is faster but returns no match? – mjwills Jan 11 '21 at 11:34
  • @mjwills good point - it depends whether these two searches look for the same data, as I mentioned in a note. It all depends on the usecase. I'll add one more note – Sergey Berezovskiy Jan 11 '21 at 12:02
  • var completedTask = await Task.WhenAny( _userManager.FindByNameAsync(userForLoginDto.UserName), _userManager.FindByIdAsync(userForLoginDto.Id)); var user = await completedTask; vr result = await _signInManager.CheckPasswordSignInAsync(user, userForLoginDto.Password, false); i found new error System.InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext – mohamedhemeda Jan 13 '21 at 07:46
  • @mohamedhemeda that's a different issue. You can start with changing lifetime of dbcontext https://stackoverflow.com/questions/48767910 or just post new question – Sergey Berezovskiy Jan 13 '21 at 10:02