共用方式為


在自動交易中表決

.NET Framework 類別和 ASP.NET 網頁可以表決 (Vote) 來認可或中止它們目前的交易。您的程式碼中缺少的外顯表決將會預設轉換為認可表決。然而,預設的認可會因為延長了每一筆交易的時間來釋放昂貴資源,而降低您應用程式的效能。

外顯表決也允許您的類別或網頁在它遭遇重大錯誤時中止交易。再者,藉著及早在交易中抓住嚴重錯誤、結束交易和釋放資源,您可以改善您的應用程式效能。

使用 AutoComplete

如果方法正常返回,System.EnterpriseServices.AutoCompleteAttribute 造成參與交易的物件表決贊成完成交易。如果方法呼叫擲回例外狀況 (Exception),則交易中止。您只能將這個屬性套用至從 ServicedComponent 類別衍生的類別。

若要使用這個功能,在類別方法之前插入屬性。如果您將屬性加入介面方法,Common Language Runtime 會忽略它。下列程式碼片段示範在交易感知類別上的屬性位置。

<Transaction(TransactionOption.Supported)> Public Class Account
   Inherits ServicedComponent
   
   <AutoComplete()> Public Sub Debit(amount As Integer)
      ' Do some database work. Any exception thrown here aborts the 
      ' transaction; otherwise, transaction commits.
   End Sub
End Class
[C#]
[Transaction(TransactionOption.Supported)]
public class Account : ServicedComponent {
    [AutoComplete]
    public void Debit(int amount) {
        // Do some database work. Any exception thrown here aborts the transaction; 
        // otherwise, transaction commits.
    }
}

使用 SetAbort 和 SetComplete

您可以使用 System.EnterpriseServices.ContextUtil 類別,它會公開 SetCompleteSetAbort 方法,來明確認可或中止交易。SetComplete 指示您的物件表決以認可它的作業;SetAbort 指示您的物件遇到問題,並表決以中止進行中的交易。交易既不認可也不中止,直到交易的根物件 (Root Object) 關閉。再者,任何參與交易物件的單一中止表決將造成整個交易失敗。

下列程式碼片段示範使用中的 SetAbortSetComplete 方法。

'Try to do something crucial to the transaction in progress.
If Not DoSomeWork() Then
   'Something goes wrong.
   ContextUtil.SetAbort()
Else
   'All goes well.
   ContextUtil.SetComplete()
End If
[C#]
//Try to do something crucial to the transaction in progress.
if( !DoSomeWork() )
{
  //Something goes wrong.
  ContextUtil.SetAbort();
}
else
{
  //All goes well.
  ContextUtil.SetComplete();
}

請參閱

自動交易