开发者

Is registering / unregistering to a .NET event a constant time operation?

开发者 https://www.devze.com 2023-03-29 18:08 出处:网络
Initially, I had assumed yes, because I understood that the invocation list for a multi-cast delegate is implemented as a linked list, which supports constant time insertion and deletion. However, sin

Initially, I had assumed yes, because I understood that the invocation list for a multi-cast delegate is implemented as a linked list, which supports constant time insertion and deletion. However, since multicast delegates are immutable, it seems that any add/remove operation would actually require the invocation list to be copied. Is this correct, or am I missing something?

Cost of registering / unregistering is of interest because I have a long-running applicatio开发者_运维知识库n that frequently registers handlers for various short-lived objects to an event, and then un-registers them just before they are disposed. The invocation list can get fairly long, so I really want this to be a constant time operation.


The invocation list can get fairly long, so I really want this to be a constant time operation.

How long is "fairly" long? Unless you're talking about thousands of subscribers, it's unlikely to be a significant period of time.

Spin up a test project and give it a go - an actual measurement trumps any number of wise old men (or women).

Update

One thought: If your specific case is for when the objects are disposed, try something like this:

public event PropertyChanged
{
    add { mPropertyChanged += value; }
    remove { mPropertyChanged -= value; }
}

public void Dispose()
{
    mPropertyChanged = null;
}

In your Dispose method, you can discard all subscriptions in one hit by just removing your reference to the stored event. This will undoubtedly be faster than unsubscribing one by one.

Yes, you're abandoning the multicast delegate to the garbage collector, but you're doing that anyway when you unsubscribe - once per unsubscription, in fact.


As per Has Passant comment Aug 22 '11 at 21:31

Adding is amortized O(1), exact same logic as List<>.Add(). Removing is O(n). You cannot change this.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号