I have an async database call inside a loop. But the database calls are happening in a sync way. I am not sure the calls are not happening in an async fashion. Any directions on what is wrong with the below code.
static async Task Main(string[] args)
{
long executionTime = 0;
await SequentialDBCallAsync();
}
private static async Task SequentialDBCallAsync()
{
DBLayer dB = new DBLayer();
for (int i = 0; i < 10; i++)
{
var product = await dB.GetDataByNameAsync("Name - 100000");
Console.WriteLine(i);
}
}
public async Task<Product> GetDataByNameAsync(string name)
{
using (var sql = new SqlConnection("Data Source=(localdb)\\ProjectsV13;Initial Catalog=Inventory;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"))
{
sql.Open();
string query = "Select id, Name from Product where Name = @name";
SqlCommand cmd = new SqlCommand(query, sql);
cmd.Parameters.Add("@name", System.Data.SqlDbType.VarChar).Value = name;
Console.WriteLine("started");
var reader = await cmd.ExecuteReaderAsync();
Console.WriteLine("executing");
while (await reader.ReadAsync())
{
var product = new Product()
{
Id = reader.GetInt32(0),
Name = reader.GetString(1)
};
return product;
}
return new Product();
}
}