Intan
Intan

Reputation: 143

Multiple TransactionScope.Complete() in a using

I have a code like this

try
{
    MyModel model = repo.GetData();
    if(model == null)
    {
       return model;
    }
    else
    {
       MyResponse response = checkData();
       if(response)
       {
           return model;
       }

       UpdateData();
    }
}
catch(Exception e)
{
    ....
}
return model;

I want to add TransactionScope like this.

try
{
   using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }))
    {
        MyModel model = repo.GetData();
        if(model == null)
        {
            return model;
        }
        else
        {
            MyResponse response = checkData();
            if(response)
            {
                return model;
            }

            UpdateData();
        }
        ts.Complete();
    }
}
catch(Exception e)
{
    ....
}
return model

And I wanna ask, is it okay if I have multiple return statement before code reach ts.Complete()? I can't set ts into null in finally block because TransactionScope is inside try block.

Upvotes: 0

Views: 1106

Answers (1)

tomludd
tomludd

Reputation: 96

To answer your question: is it ok to return before trans.Complete()? - Yes, it is. Transaction will not be commited and changes will not be applied. That is how it works.

The using statement will run .Dispose() in any senarios even when an exception is happening (or return).

When disposing a transaction it will be committed if trans.Complete() was called, and no changes will apply if not called.

About using statement: What is the C# Using block and why should I use it?

About Transaction.Dispose(): https://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.dispose(v=vs.110).aspx

Upvotes: 1

Related Questions