我编写了一个程序以异步方式执行数据库操作。我尝试使用 BeginTransaction() 或 TransactionScope 在数据库事务中运行它,但没有运气。我单步执行了 VS2012 中的代码,并注意到当它看到 ExecuteNonQueryAsync 的等待时,执行会跳出 foreach 循环。
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();
}
}
已编辑:包括方法标头/签名。