PLS HELP! Override default event behavior (add/remove)

M

MuZZy

Hi,

I need to do some custom processing of event handlers assigned to a
particular event in my user control, e.g. when you add a handler it
should first remove it to make sure any given handler is not added twice
thruout the application. I was told i can use declaration of an event in
the form:

public event SelectedValueChangedHandler SelValueChanged
{
add
{
...
}
remove
{
...
}
}

but how do i really use it? Could anyone please give an example?
Amazingly google didn't show almost any info on that. Is it uncommon to
override add/remove for events?

Any ideas/comments are highly appreciated!

Thank you,
MuZZy
 
G

Guest

Hi Muzzy,

hope the following code snippet helps you understand it.

George

using System;
using System.ComponentModel;

public class EventListDemo
{
private EventHandlerList eventList = new EventHandlerList();
private static object somethingHappenedEvent = new object();

public event EventHandler SomeThingHappened
{
add { eventList.AddHandler(somethingHappenedEvent, value); }
remove { eventList.RemoveHandler(somethingHappenedEvent, value); }
}
}
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,


Personally I have never done it, but I know other people do it ( like Jon
Skeet) he has said in several thread that he overwrite it.
The reason is that the default implementation block on this : lock(this) and
this is not the best approach in multithreading. IIRC he does explain it
furhter in his site

Remember to use a locking statement to prevent concurrency problems
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top