I understand that we should use async and await when accessing a database as it takes time to process this request, and we want the program to get on with other tasks while it waits.
However, I'm not sure WHERE to make this await call.
Should the high-level module calling the low-level database access module use await, or should the low-level module use it?
I'm thinking that it should be the high-level module, as that has more stuff to do???
Some example code is below, right or wrong place to use the command?
High-level controller module:
public async Task<IActionResult> Delete(int id, string email)
{
email = email.ToLower();
IUsers user = new Users();
// Async Await call here or in lower level module???
bool del = await Task.Run(() => user.DeleteUser(id, email));
if (del == true)
{
System.Diagnostics.Debug.WriteLine(String.Format("User Deleted"));
return Ok();
}
else
{
// If del is false or null
System.Diagnostics.Debug.WriteLine("Error. User ID: {0} Email: {1} didn't match, not deleted. ", id, email));
return BadRequest();
}
}
Low-Level Database Access Module:
// Connection String
IDbConnection dbConnection = new MySqlConnection(@"Server=127.0.0.1;blah;");
bool IUsers.DeleteUser(int id, string email)
{
using (dbConnection)
{
try
{
string cmd = @"DELETE from users WHERE ID=@Id AND EMAIL=@Email";
bool result = false;
// Should async await maybe be here???
var del = dbConnection.Execute(cmd, new { Id = id, Email = email });
//Change result to True if execute command went ahead
result = del > 0;
// Returns True or False
return result;
}
catch (Exception ex)
{
Console.WriteLine("Exception in Users.DeleteUser");
Console.WriteLine("Exception: {0}", ex.Message);
return false;
}
}
}
Thanks for the feedback!