Page 1 of 1

TransactionScope in Threads

Posted: Fri 27 Mar 2015 05:43
by michael_lamothe
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.

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());
}
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?

Re: TransactionScope in Threads

Posted: Fri 27 Mar 2015 16:14
by Shalex
Please try

Code: Select all

new TimeSpan(0, 0, 5)
Sleep(5200)
instead of

Code: Select all

new TimeSpan(0, 0, 1)
Sleep(1200)
1 second (TimeSpan after which the transaction scope times out and aborts the transaction) is less than the time needed for initialization of EF context and retrieving data. That's why you are getting the errors.

If this doesn't explain the behaviour you have encountered, send us your:
1) Log.txt
2) EF version
3) template used (with its non-default settings)
4) are you using OCI (via Oracle client) or Direct mode?

Re: TransactionScope in Threads

Posted: Sat 28 Mar 2015 21:01
by michael_lamothe
Thanks Shalex. That was the issue, exactly! Thank you for your time.