TransactionScope in Threads
Posted: Fri 27 Mar 2015 05:43
We've been using dotConnect for Oracle (Professional) for years on our web server. We've been trying to debug an intermittent issue that I believe that I have replicated the issue in a console application. The issue seems to come from using transactions in different threads at the same time. Here's the code I used to reproduce the issue.
In the resulting file you will see 3 exceptions rather than 1. Can someone explain why that is? Shouldn't the "using" destroy the TransactionScope?
Code: Select all
static void Main(string[] args)
{
File.WriteAllText(@"C:\Log.txt", "");
var threads = new List<System.Threading.Thread>();
for (int i = 0; i < 3; i++)
{
var thread = new System.Threading.Thread((object arg) =>
{
int j = (int)arg;
try
{
var e = new Entities();
using (var transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew, new TimeSpan(0, 0, 1)))
{
if (j == 0)
{
System.Threading.Thread.Sleep(1200);
}
var property = e.Properties.Single(x => x.Id == 22);
property.LastUpdateDate = DateTime.Now;
e.SaveChanges();
transactionScope.Complete();
}
}
catch (Exception ex)
{
lock (typeof(Program))
{
File.AppendAllText(@"C:\Log.txt", string.Format("{0}: {1}\r\n", DateTime.Now, ex));
}
}
});
thread.Start(i);
}
threads.ForEach(x => x.Join());
}