Код: Выделить всё
[TestClass]
public class MyIntegrationTest : IntegrationTestsBase {
[TestMethod]
public void SaveTwoDocumentsSimultaneously_WorkSuccessfully()
{
//Assign
var doc1 = new Document() {Number = "Test1"};
var doc2 = new Document() {Number = "Test2"};
//action
CountdownEvent countdown = new CountdownEvent(2);
ThreadPool.QueueUserWorkItem(WorkerThread, new object[] { Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete), doc1, countdown });
ThreadPool.QueueUserWorkItem(WorkerThread, new object[] { Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete), doc2, countdown });
countdown.Wait();
//assert
//assertion code for chack two document inserted
....
}
}
Код: Выделить всё
[TestClass]
public abstract class IntegrationTestsBase
{
private TransactionScope _scope;
[TestInitialize]
public void Setup()
{
this._scope = new TransactionScope(TransactionScopeOption.Required,
new System.TimeSpan(0, 10, 0));
}
[TestCleanup]
public void Cleanup()
{
this._scope.Dispose();
}
}
Код: Выделить всё
private static void WorkerThread(object state)
{
if (state is object[] array)
{
var transaction = array[0];
var document = array[1] as Document;
CountdownEvent countdown = array[2] as CountdownEvent;
try
{
//Create a DependentTransaction from the object passed to the WorkerThread
DependentTransaction dTx = (DependentTransaction)transaction;
//Sleep for 1 second to force the worker thread to delay
Thread.Sleep(1000);
//Pass the DependentTransaction to the scope, so that work done in the scope becomes part of the transaction passed to the worker thread
using (TransactionScope ts = new TransactionScope(dTx))
{
//Perform transactional work here.
using (var ctx = new PlanningDbContext())
{
ctx.Documents.Add(doc);
ctx.SaveChanges(); // System.Data.Entity.Core.UpdateException: произошла ошибка при обновлении записей. Подробности смотрите во внутреннем исключении. ---> System.Transactions.TransactionException: операция недопустима для состояния транзакции.
Где в моем коде приводит к этой ошибке и как мне это решить?
Подробнее здесь: [url]https://stackoverflow.com/questions/79045806/integration-test-error-when-run-simultaneously-tasks-in-transaction[/url]
Мобильная версия