Transaction over Threads

9 באוגוסט 2006

no comments

When you start a transaction scope, and inside you start another thread. How can you commit or rollback your transaction based on the other thread results?

System.Transactions.DependentTransaction is your friend…


class Program


    public static void ThreadProc(object o)


        DependentTransaction dtx = (DependentTransaction)o;


        using (TransactionScope s = new TransactionScope(dtx))


            // Ensure this thread completes after the main one.



            Console.WriteLine("Before completing dependent transaction scope");




        Console.WriteLine("After completing dependent transaction scope ");




    static void Main(string[] args)


        DependentTransaction dtx;

        Thread newThread = new Thread(new ParameterizedThreadStart(Program.ThreadProc));


        using (TransactionScope s = new TransactionScope())


            dtx = Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete);   


            Console.WriteLine("About to complete the main thread");




        Console.WriteLine("Transaction Completed");




The results will be:

About to complete the main thread

Before completing dependent transaction scope

After completing dependent transaction scope

Transaction Completed

This means that the main thread's transaction scope was waiting for the other thread scope to be closed before completing.


I find it very useful!



Add comment
facebook linkedin twitter email