Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8712703
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T05:09:45+00:00 2026-06-13T05:09:45+00:00

I have a problem with multithreaded transaction and entity framework. I have a thread,

  • 0

I have a problem with multithreaded transaction and entity framework. I have a thread, which operates in transaction and I would like to have a few more worker threads working within same transaction. The following code illustrates situation (there is one dummy entity in EF context, the code basically spawns 5 threads, I would like to insert some entities within each thread and at the end in main thread, I would like to continue working with DB, but to keep whole process isolated in ONE transaction):

using(var scope = new TransactionScope())
{
    int cnt = 5;
    ManualResetEvent[] evt = new ManualResetEvent[cnt];

    for(int i = 0; i < cnt; i++)
    {
        var sink = new ManualResetEvent(false);
        evt[i] = sink;

        var tr = Transaction.Current.DependentClone(
            DependentCloneOption.BlockCommitUntilComplete);

        Action run = () =>
        {
            using (var scope2 = new TransactionScope(tr))
            {
                using (var mc = new ModelContainer())
                {
                    mc.EntitySet.Add(new Entity()
                    {
                        MyProp = "test"
                    });
                    mc.SaveChanges();
                }
            }

            sink.Set();
        };

        ThreadPool.QueueUserWorkItem(r => run());
    }

    ManualResetEvent.WaitAll(evt);

    using (var mc = new ModelContainer())
    {
        Console.WriteLine(mc.EntitySet.Count());
    }
    Console.ReadKey();
}

The problem is, that exception is thrown on mc.SaveChanges();. Inner exception is TransactionException: “The operation is not valid for the state of the transaction.” It seems that at some point, transaction is aborted. I think it is after first thread calls SaveChanges(), but Im not sure. Any idea why transaction is aborted?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T05:09:46+00:00Added an answer on June 13, 2026 at 5:09 am

    I discovered what was the problem happening here. Based on this article, I found that it is impossible to work with two MSSQL server connections within one transaction at the same time. I also discovered that I was not properly handling dependent transaction in previous code. My working illustration code follows:

        class Context
        {
            public ManualResetEvent sink;
            public DependentTransaction transaction;
        }
    
        static object syncRoot = new object();
    
        static void Main(string[] args)
        {
            using (var scope = new TransactionScope())
            {
                int cnt = 5;
                ManualResetEvent[] evt = new ManualResetEvent[cnt];
    
                for (int i = 0; i < cnt; i++)
                {
                    var sink = new ManualResetEvent(false);
                    evt[i] = sink;
    
                    var context = new Context()
                    {
                        // clone transaction
                        transaction = Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete),
                        sink = sink
                    };
    
                    ThreadPool.QueueUserWorkItem(new WaitCallback(Run), context);
                }
    
                // wait for all threads to finish
                ManualResetEvent.WaitAll(evt);
    
                using (var mc = new ModelContainer())
                {
                    // check database content
                    Console.WriteLine(mc.EntitySet.Count());
                }
    
                // after test is done, the transaction is rolled back and the database state is untouched
                Console.ReadKey();
            }
        }
    
        static void Run(object state)
        {
            var context = state as Context;
    
            // set ambient transaction
            Transaction oldTran = Transaction.Current;
            Transaction.Current = context.transaction;
    
            using (var mc = new ModelContainer())
            {
                mc.EntitySet.Add(new Entity()
                {
                    MyProp = "test"
                });
    
                // synchronize database access
                lock (syncRoot)
                {
                    mc.SaveChanges();
                }
            }
    
            // release dependent transaction
            context.transaction.Complete();            
            context.transaction.Dispose();
    
            Transaction.Current = oldTran;
    
            context.sink.Set();            
        }
    }
    

    It is probably not very nice way of writing multithreaded bussiness layer, but this shared transaction approach is WERY useful for testing in my case. The only modification need to make this work is to override Db context and synchronize save method in test runs.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this weird problem with my (multithreaded) server when I get more than
I have a multithreaded application in which my thread utilization is very poor (in
We have a WinForms desktop application, which is heavily multithreaded. 3 threads run with
I have problem with python multithreaded Queues. I have this script, where producer take
I have essentially the same problem discussed here: http://khason.net/blog/dependency-property-getters-and-setters-in-multithreaded-environment/ public static readonly DependencyProperty MyPropertyProperty
I have the following problem: Multithreaded WPF application, Model View Presenter Implementation. Presenters and
I have multithreaded application and I've got a little problem when application ends: I
We have a (very) multithreaded application that would pass all unit tests, but would
I have an app which creates a thread which communicate with the main UI
I have a multithreaded C program, which consistently generates a segmentation fault at a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.