I have written a program to perform database operations in asynchronous fashion. I try to run it in a database transaction using BeginTransaction() or TransactionScope but have no luck. I stepped through the code in VS2012 and noticed the execution would jump out the foreach loop when it sees the await for ExecuteNonQueryAsync.
public delegate void CallBackMethod();
public async Task MyFunction(List<string> items, CallBackMethod functionToCallBeforeCommitTransaction)
{
using (TransactionScope trans = new TransactionScope(
TransactionScopeOption.RequiresNew,
TransactionScopeAsyncFlowOption.Enabled ))
{
using (SqlConnection conn = new SqlConnection(myConnectionString))
{
await conn.OpenAsync();
foreach (string item in items)
{
SqlCommand cmd = new SqlCommand("MySproc", conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ItemID", item);
await cmd.ExecuteNonQueryAsync();
// ^^^ Execution jumps out here and returns back to the calling function.
// No exception was raised. It did not continue the loop.
}
}
functionToCallBeforeCommitTransaction();
trans.Complete();
}
}
Edited: Includes method header/signature.