我想在TransactionScope中运行任务,我通过80个保存任务处理了400,000条记录(每次保存5000条记录)这是我的代码:
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew, TimeSpan.MaxValue))
{
try
{
var tasks = new List<Task>();
foreach (var empsGroup in empsGroups)
{
tasks.Add(Task.Run(() =>
{
//add save of 5000 records
}
}
Task allTasks = Task.WhenAll(tasks.ToArray());
try
{
allTasks.Wait();
}
catch (Exception e)
{
scope.Dispose();
}
scope.Complete();
}
catch (Exception e)
{
scope.Dispose();
}
}
但是我有例外:
message: System.Transactions.TransactionAbortedException: The transaction has aborted. ---> System.TimeoutException: Transaction Timeout
--- End of inner exception stack trace ---
at System.Transactions.TransactionStateAborted.BeginCommit(InternalTransaction tx, Boolean asyncCommit, AsyncCallback asyncCallback, Object asyncState)
at System.Transactions.CommittableTransaction.Commit()
at System.Transactions.TransactionScope.InternalDispose()
at System.Transactions.TransactionScope.Dispose()
1)增加超时时间。您可能需要将其增加得很高,并且长时间运行的事务可能会干扰数据的其他使用。
2)提高性能(例如添加索引或CPU)以满足超时要求。如果要移动那么多数据,可能不可行。
3)删除使用交易的要求。很多时候,您可以通过插入到临时表中来避免长时间运行的事务,例如,将其作为单个SQL插入的暂存区(其运行速度比成千上万个任务快得多)。
在大多数情况下,第三个选择是我的首选。