I have following code. the call to connection.OpenAsync() quits the program without any exception. Even the finally on the caller method is not invoked. program is targetting .NET45 Any idea?
Update: Here is the parent code that works with .Wait(). It quits without .Wait() in parent code when connection.OpenAsync() is called in the child method below.
static void Main(string[] args)
{
UpdateSqlDatabase updateSqlDatabase = new UpdateSqlDatabase(args);
updateSqlDatabase.UpdateDatabaseSchemaAsync().Wait();
}
After a series of async method calls:
public async Task<T> ExecuteQueryAsync<T>(string connectionString, string commandText, IDictionary<string, object> parameters, Func<SqlDataReader, T> rowMapFunc)
{
using (var connection = new SqlConnection(connectionString))
{
try
{
await connection.OpenAsync();
}
catch (Exception ex)
{
}
SqlCommand command = connection.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = commandText;
if (parameters != null)
{
foreach (var item in parameters)
{
command.Parameters.AddWithValue(item.Key, item.Value);
}
}
SqlDataReader reader = await command.ExecuteReaderAsync();
T retObj = default(T);
while (await reader.ReadAsync())
{
retObj = rowMapFunc(reader);
}
return retObj;
}
}
So the issue was that in the code I had chain of async calls but the parent (main) method was not async and did not have await causing the program to quit when Async was called by one of the child method. I added .Wait() to the call to the async method from main method (which is sync) and it worked fine.
Thanks!