So I'm trying to turn my synchronous method to asnych. The set up is - I have a method that check if an user uses any of the company products. I need different query for each product so I decided to try and give a shot to the asnych programming since I've never tried using Task and await before even though, maybe this is not the perfect situation to do it. But however now I've changed my method to this:
private static async Task<bool> isUsingProducts(int clientId)
{
bool hasProduct = false;
using (SqlConnection connection1 = new SqlConnection(connString))
{
SqlCommand firstProduct = new SqlCommand(firstQuery, connection1);
firstProduct.CommandTimeout = 300;
firstProduct.Open();
Task numberOfUsedProducts1 = firstProduct.ExecuteScalarAsync();
//int numberOfUsedProducts = (int)firstProduct.ExecuteScalar();
//if (0 < numberOfUsedProducts)
//{
// hasProduct = true;
//}
}
using (SqlConnection connection2 = new SqlConnection(connString))
{
SqlCommand secondProduct= new SqlCommand(secondQuery, connection2);
secondProduct.CommandTimeout = 300;
connection2.Open();
Task numberOfUsedProducts2 = secondProduct.ExecuteScalarAsync();
//int numberOfUsedProducts = (int)secondProduct.ExecuteScalar();
//if (0 < numberOfUsedProducts)
//{
// hasProduct = true;
//}
}
return hasProduct;
}
Basically this is some mix from what I've tried and what has left from the previous method which was synchronous. In this case I only care if the user is using ANY of the products or not so I was checking after the end of each query. However sometimes I'm gonna need the actual count so at the end I want to be able to execute the queries in asnych mode and later decied how exactly i'm gonna deal with the results.
Right now this:
Task numberOfUsedProducts2 = secondProduct.ExecuteScalarAsync();
is not giving me an error, but I don't know how to proceed. What I don't know how to do is how to add the logic for checking the result of each query (the queries are synch so how shall I know that there's a result already) and how to convert those result to the actual type (int)?