意图:使用事务提交/回滚支持加快support操作
发行:
看起来事务范围不能支持这样的Task.WhenAll,因此,如果在执行过程中出现错误,中间写就不会回滚。
Q:,所以我想知道它是可以工作的,还是利用事务范围的不合适的方式?
public void Upsert(IEnumerable<IEnumerable<Item>> splitPerConnection, DateTime endDate)
{
using (var scope = _transactionScopeFactory.Create(TransactionScopeOption.Required))
{
try
{
UpdateEndDate(endDate);
var insertTasks = splitPerConnection.Select(ch => Task.Run(() => Insert(ch)));
Task.WhenAll(insertTasks).GetAwaiter().GetResult();
scope.Complete();
}
catch (Exception ex)
{
throw ex;
}
}
}
private int Insert(IEnumerable<Item> items)
{
int affectedRows;
using (var scope = _transactionScopeFactory.Create(TransactionScopeOption.Required))
using (var sqlConnection = new SqlConnection(DockerMsSqlServerConnectionString))
{
sqlConnection.Open();
affectedRows = sqlConnection.Execute(ItemsQueries.Insert, items, commandTimeout: 0);
scope.Complete();
}
return affectedRows;
}
private int UpdateEndDate(DateTime endDate)
{
int affectedRows;
using (var scope = _transactionScopeFactory.Create(TransactionScopeOption.Required))
using (var sqlConnection = new SqlConnection(DockerMsSqlServerConnectionString))
{
sqlConnection.Open();
affectedRows = sqlConnection.Execute(ItemsQueries.UpdateEndDate, new { EndDate = endDate }, commandTimeout: 0);
scope.Complete();
}
return affectedRows;
}发布于 2022-03-17 09:40:06
您可以尝试利用SqlBulkCopy,而不是将项拆分到不同的连接对象上。
您可以通过修改IEnumerable<Item>创建数据集。所有的并行操作都可以在这里应用到从IEnumerable<Item>到dataset的转换。一旦创建了dataset,SqlBulkCopy将帮助您。您可以创建3-4组数据集,并执行3-4次插入查询。
在这种方法中,您可以维护一个数据库连接,它也有助于跟踪数据库事务的ACID遵从性。
https://stackoverflow.com/questions/71508836
复制相似问题