如何:宣告自訂事件以節省記憶體 (Visual Basic)How to: Declare Custom Events To Conserve Memory (Visual Basic)

在幾種情況下,應用程式將其記憶體使用量保持在較低的情況是很重要的。There are several circumstances when it is important that an application keep its memory usage low. 自訂事件可讓應用程式僅針對它所處理的事件使用記憶體。Custom events allow the application to use memory only for the events that it handles.

根據預設,當類別宣告事件時,編譯器會為欄位配置記憶體來儲存事件資訊。By default, when a class declares an event, the compiler allocates memory for a field to store the event information. 如果類別有許多未使用的事件,它們就會不必要地佔用記憶體。If a class has many unused events, they needlessly take up memory.

您可以使用自訂事件,更仔細地管理記憶體使用量,而不是使用 Visual Basic 所提供的預設事件執行。Instead of using the default implementation of events that Visual Basic provides, you can use custom events to manage the memory usage more carefully.

範例Example

在此範例中,類別會使用儲存在 [Events] 欄位中 EventHandlerList 類別的一個實例,來儲存所使用之事件的相關資訊。In this example, the class uses one instance of the EventHandlerList class, stored in the Events field, to store information about the events in use. EventHandlerList 類別是設計用來保存委派的優化清單類別。The EventHandlerList class is an optimized list class designed to hold delegates.

類別中的所有事件都會使用 [Events] 欄位,來追蹤哪些方法正在處理每個事件。All events in the class use the Events field to keep track of what methods are handling each event.

Public Class MemoryOptimizedBaseControl
    ' Define a delegate store for all event handlers.
    Private Events As New System.ComponentModel.EventHandlerList

    ' Define the Click event to use the delegate store.
    Public Custom Event Click As EventHandler
        AddHandler(ByVal value As EventHandler)
            Events.AddHandler("ClickEvent", value)
        End AddHandler
        RemoveHandler(ByVal value As EventHandler)
            Events.RemoveHandler("ClickEvent", value)
        End RemoveHandler
        RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
            CType(Events("ClickEvent"), EventHandler).Invoke(sender, e)
        End RaiseEvent
    End Event

    ' Define the DoubleClick event to use the same delegate store.
    Public Custom Event DoubleClick As EventHandler
        AddHandler(ByVal value As EventHandler)
            Events.AddHandler("DoubleClickEvent", value)
        End AddHandler
        RemoveHandler(ByVal value As EventHandler)
            Events.RemoveHandler("DoubleClickEvent", value)
        End RemoveHandler
        RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
            CType(Events("DoubleClickEvent"), EventHandler).Invoke(sender, e)
        End RaiseEvent
    End Event

    ' Define additional events to use the same delegate store.
    ' ...
End Class

另請參閱See also