You can mix system.transaction configuration settings and the use of the TransactionOption
class, but there are some things you need to be aware of.
If you use the TransactionOption
and
specify a Timeout
value, that value
will be used over the
system.transactions/defaultTimeout
value.
The above is the crux of the problem in your case I think. You are using the TransactionOption
to specify the isolation level, and as a side effect you are getting an infinite Timeout value because infinite is the default Timeout value for TransactionOption
if its not specified. Though, I'm not quite sure why that is...it would make sense to default to the default Transaction Timeout.
You can implement your own TransactionOptions helper class that includes defaults that are read from app.config (if found) or default to reasonable values for a TransactionOption class that can be used.
In any case, you can still limit this by using the system.transaction/machineSettings/maxTimeout value. This is an administrative setting and can only be configured through the machine.config. You'll get a ConfigurationException if you try it from app/web.config.
<system.transactions>
<machineSettings maxTimeout="00:00:30" />
</system.transactions>
With the maxTimeout set, no matter what timeout value you specify, the maximum value will be limited to the maxTimeout value. The default maxTimeout is 00:10:00, or 10 minutes, so you wouldn't actually ever have an infinite timeout on a transaction.
You can also set the transaction IsolationLevel explicitly on the database connection you are using within the transaction. Something like this?
var connectionString = "Server=.;Database=master;Trusted_Connection=True;";
using (var scope = new TransactionScope(TransactionScopeOption.Required))
{
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
var sqlTransaction = conn.BeginTransaction(System.Data.IsolationLevel.Serializable);
// do database work
//
sqlTransaction.Commit();
}
// do other work..
//
scope.Complete();
}
In your testing, you may need to make sure you rebuild so that the app.config is regenerated . In my testing, it appeared that I needed to terminate the *.vshost.exe process in order for it to pick up the system.transaction configuration setting change - though I feel that may have been a fluke. Just fyi..
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…