C
C#13mo ago
Aokiri 🐸

Difference between await & GetAwaiter()/GetResult()

I'm actually doing a simple task that checks if a role exists in the database and create it if the role doesn't exists. Code:
if (!_roleManager.RoleExistsAsync(SD.Role_Customer).GetAwaiter().GetResult())
{
_roleManager.CreateAsync(new IdentityRole(SD.Role_User)).GetAwaiter().GetResult();
_roleManager.CreateAsync(new IdentityRole(SD.Role_Moderator)).GetAwaiter().GetResult();
_roleManager.CreateAsync(new IdentityRole(SD.Role_Admin)).GetAwaiter().GetResult();
_roleManager.CreateAsync(new IdentityRole(SD.Role_Invited)).GetAwaiter().GetResult();
}
if (!_roleManager.RoleExistsAsync(SD.Role_Customer).GetAwaiter().GetResult())
{
_roleManager.CreateAsync(new IdentityRole(SD.Role_User)).GetAwaiter().GetResult();
_roleManager.CreateAsync(new IdentityRole(SD.Role_Moderator)).GetAwaiter().GetResult();
_roleManager.CreateAsync(new IdentityRole(SD.Role_Admin)).GetAwaiter().GetResult();
_roleManager.CreateAsync(new IdentityRole(SD.Role_Invited)).GetAwaiter().GetResult();
}
Here's how it looks like with await:
if (!await _roleManager.RoleExistsAsync(SD.Role_Customer).GetAwaiter().GetResult())
{
await _roleManager.CreateAsync(new IdentityRole(SD.Role_User));
await _roleManager.CreateAsync(new IdentityRole(SD.Role_Moderator));
await _roleManager.CreateAsync(new IdentityRole(SD.Role_Admin));
await _roleManager.CreateAsync(new IdentityRole(SD.Role_Invited));
}
if (!await _roleManager.RoleExistsAsync(SD.Role_Customer).GetAwaiter().GetResult())
{
await _roleManager.CreateAsync(new IdentityRole(SD.Role_User));
await _roleManager.CreateAsync(new IdentityRole(SD.Role_Moderator));
await _roleManager.CreateAsync(new IdentityRole(SD.Role_Admin));
await _roleManager.CreateAsync(new IdentityRole(SD.Role_Invited));
}
6 Replies
Angius
Angius13mo ago
.GetAwaiter().GetResult() is blocking The one and only proper way to call asynchronous code is with await No maybes, no perhapses
jcotton42
jcotton4213mo ago
$deadlock
MODiX
MODiX13mo ago
Don't Block on Async Code
This is a problem that is brought up repeatedly on the forums and Stack Overflow. I think it’s the most-asked question by async newcomers once they’ve learned the basics.
jcotton42
jcotton4213mo ago
Also see $nothread
MODiX
MODiX13mo ago
There Is No Thread
This is an essential truth of async in its purest form: There is no thread.
Aokiri 🐸
Aokiri 🐸OP13mo ago
Thanks a lot. I'll read about it and then modify the code.
Want results from more Discord servers?
Add your server