As I know it's recommended to put lock for custom event add/remove methods. Also when C# compiles event it refers to the internally created delagate field. I need to use not event but private delegate and public Add/Remove methods, should I also use locks in this case as shown in the code below?
private EventHandler _delegate;
public void Add(EventHandler e)
{
lock(_locker)
{
_delegate += e;
}
}
public void Remove(EventHandler e)
{
lock(_locker)
{
_delegate -= e;
}
}
UPD after comments: why I still need (or I don't?) to use lock with following implementation where I use custom event's add/remove but delegate variable and not event variable inside:
private EventHandler _delegate;
public event EventHandler MyEvent
{
add
{
lock (_locker)
{
_delegate += value;
}
}
remove
{
lock (_locker)
{
_delegate += value;
}
}
}
UPD2: I do not think it's duplicated question because I asked not about standard obj.myEvent += onMyEventHandler thread safety (this is answered) but rather about add/remove accessors of event and about custom Add(), Remove() methods.