开发者

Clearing C# Events after execution?

Say I have the following code:

public event EventHandler DatabaseInitialized = delegate {};

//a intederminant amount of subscribers have subscribed to this event...


// sometime later fire the ev开发者_StackOverflowent, then create a new event handler...
DatabaseInitialized(null,EventArgs.Empty);

//THIS LINE IS IN QUESTION    
DatabaseInitialized = delegate {};

Will this clear out the subscribers, replacing it with new empty default? And, will the event notify all subscribers before they get cleared out? I.E. Is there a chance for a race condition?


Yes it will clear it out. And because events fire syncronously in the same thread there shouldn't be race condition.

My advice: when in doubt, write a small test application and... well, test it.

UPDATE: I tested it before posting. (In response to minuses.)


To unsubscribe from the event use event-=delegate, so you're sure that resource is free. Even if by official Microsoft documentation it's not necessary, in my own experience, especially on a large scale complex project, unnecessary events suscribers are source for memory leaks. So unsubscribe from them explicitly.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜