Good I have a big mess with asynchronous programming. When I query the API of an online store, I always use the await
. When I implement these in a method, I always return the result with Task<T>
. However, when I try to do the same thing with queries to a database, I get the error:
Error CS1061 "int" does not contain a definition for "GetAwaiter" or an accessible extension method "GetAwaiter" that accepts a first argument of type "int" (are you missing a using directive or an assembly reference?) An example of what i try to do:
public async Task<Int32> ObteNumFills()
{
Int32 nRegs = 0;
string connectionString = Cconnexio.RetornaCadenaConnexio(BddParams);
string query= "Select COUNT(codigo) FROM empleados where edad > 24;
using (SqlConnection cn = new SqlConnection(connectionString))
{
cn.Open();
SqlCommand cmd = new SqlCommand(query, cn);
try
{
nRegs = await(Int32)cmd.ExecuteScalar();
}
catch (Exception e)
{
nRegs = 0;
}
}
return nRegs;
}
This query is very simple and shouldn't take more than a few milliseconds, but how could I perform this task asynchronously?
You have to use the async methods
cn.OpenAsync()
andcmd.ExecuteScalarAsync()