Transaction over Threads

9 באוגוסט 2006

tags:
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.


            Thread.Sleep(10000);


 


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


            s.Complete();


        }


 


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


        dtx.Complete();


    }


 


    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);   


            newThread.Start(dtx);


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


            s.Complete();                          


        }


 


        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!


 


Enjoy!

Add comment
facebook linkedin twitter email