![](/img/trans.png)
[英]Calling TransactionScope.Complete when executing multiple sql statements in DAL
[英]Multiple TransactionScope.Complete() in a using
我有這樣的代碼
try
{
MyModel model = repo.GetData();
if(model == null)
{
return model;
}
else
{
MyResponse response = checkData();
if(response)
{
return model;
}
UpdateData();
}
}
catch(Exception e)
{
....
}
return model;
我想這樣添加TransactionScope
。
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
我想問,在代碼到達ts.Complete()
之前是否有多個return
語句可以嗎? 我不能在finally
塊中將ts
設置為null,因為TransactionScope
在try塊內。
要回答您的問題:在trans.Complete()之前可以返回嗎? - 是的。 不會提交事務,並且不會應用更改。 這就是它的工作原理。
using語句將在任何情況下運行.Dispose(),即使發生異常(或返回)也是如此。
處置事務時,如果調用了trans.Complete(),則將提交該事務;如果未調用,則將不應用任何更改。
關於using語句: 什么是C#Using塊,為什么要使用它?
關於Transaction.Dispose(): https : //msdn.microsoft.com/zh-cn/library/system.transactions.transactionscope.dispose ( v= vs.110) .aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.