共用方式為


註冊暫時性訂閱

暫時性訂閱會針對已經存在的特定訂閱者物件要求事件。 暫時性訂閱會儲存在 COM+ 目錄中,但如果事件系統或作業系統停止,則會刪除訂閱。 不同於持續性訂閱,暫時性訂閱會系結至特定物件,而且只會儲存在事件系統中。 如果事件系統或操作系統發生問題,訂用帳戶就會消失。 暫時性訂閱比持續性訂閱更有效率,但您必須管理其物件生命週期。

無法使用元件服務管理工具來設定暫時性訂閱。 您必須使用 COM+ 系統管理介面來建立或更新暫時性訂閱。

Visual Basic

下列程序說明如何使用 Microsoft Visual Basic 建立暫時性訂閱:

  1. 將新的專案新增至 TransientSubscriptions 集合,並將 SubscriberInterface 屬性設定為訂閱者物件的 IUnknown 介面,以指定訂閱者為暫時性。 COM+ 事件不會在引發事件時建立訂閱者物件的新實例,而是會改用您指定的實例。 COM+ 事件會保存訂閱者對象的參考計數,直到從系統移除訂閱為止。

  2. 建立 COM+ 伺服器應用程式(.exe、.dll或 .ocx 檔案),其物件會實作您想要訂閱的介面或方法。

  3. 使用下列程式代碼建立您的暫時性訂閱,方法是傳入事件類別物件的 CLSID 和訂閱者對象的實例。 使用元件服務系統管理工具,您可以以滑鼠右鍵按兩下 COM+ 元件、選取 [屬性],然後選取 [一般] 索引標籤,以取得 EventCLSID 屬性。

    Public Function CreateTransientSubscription( _
      ByVal clsid As String, ByVal objref As Object) As String 
        Dim oCOMAdminCatalog As COMAdmin.COMAdminCatalog
        Dim oTSCol As COMAdminCatalogCollection
        Dim oSubscription As ICatalogObject
        Dim objvar As Variant
        On Error GoTo CreateTransientSubscriptionError
        Set oCOMAdminCatalog = CreateObject("COMAdmin.COMAdminCatalog")
        'Gets the TransientSubscriptions collection
        Set oTSCol = oCOMAdminCatalog.GetCollection( _
          "TransientSubscriptions")
        Set oSubscription = oTSCol.Add
        Set objvar = objref
        oSubscription.Value("SubscriberInterface") = objref
        oSubscription.Value("EventCLSID") = clsid
        oSubscription.Value("Name") = "TransientSubscription"
        oTSCol.SaveChanges
        CreateTransientSubscription = oSubscription.Value("ID")
        Set oSubscription = Nothing
        Set oTSCol = Nothing
        Set oCOMAdminCatalog = Nothing
        Set objvar = Nothing
        Exit Function
    CreateTransientSubscriptionError:
        CreateTransientSubscription = ""
        Err.Raise Err.Number, "[CreateTransientSubscription]" & _
          Err.Source, Err.Description
    End Function
    

下列範例說明如何呼叫 CreateTransientSubscription 函式來訂閱名為 IStockTicker 的介面,其方法稱為 UpdateStock。

  1. 建立支援介面 IStockTicker 的事件類別,其有一個方法 UpdateStock。

  2. 在您的訂閱者專案中,新增實作 IStockTicker 介面的類別。

  3. 當您要訂閱時,請執行下列程式代碼:

    Dim oMyTicker As Object
    Dim sSubscriptionID As String
    Set oMyTicker = CreateObject("TheProject.CMyTicker")
    sSubscriptionID = CreateTransientSubscription( _
      "{..CLSID for the Event Class..}", oMyTicker)
    

CreateTransientSubscription 函式會傳回字串,此字串是 GUID,可用來做為句柄或 Cookie,以便稍後撤銷訂閱。 若要移除訂閱,請在 TransientSubscriptions 集合上呼叫 COM 管理員 CatalogCollection 的 Remove 方法,並傳入與先前收到的 GUID 對應的索引。

註冊訂用帳戶