F
Fred West
I have an object with events that are subscribed to, from different threads.
My code currently looks like this:
private event MyEventHandler myEvent = null;
public event MyEventHandler MyEvent
{
add {myEvent += value;}
remove {myEvent -= value;}
}
FIRST QUESTION: Do I need to lock in the add and remove? Such as:
private myEventLock = new object();
private event MyEventHandler myEvent = null;
public event MyEventHandler MyEvent
{
add {lock(myEventLock) {myEvent += value;}}
remove {lock(myEventLock) {myEvent -= value;}}
}
I could have two threads subscribing at the same time. Thus I wonder if it's
possible one subscription could get lost if I do not lock.
SECOND QUESTION: Do I need to lock when calling the event? Such as:
lock (myEventLock) {if (myEvent!=null) myEvent();}
Or does the C# compiler handle all these details for you. Thanks,
- Fred
My code currently looks like this:
private event MyEventHandler myEvent = null;
public event MyEventHandler MyEvent
{
add {myEvent += value;}
remove {myEvent -= value;}
}
FIRST QUESTION: Do I need to lock in the add and remove? Such as:
private myEventLock = new object();
private event MyEventHandler myEvent = null;
public event MyEventHandler MyEvent
{
add {lock(myEventLock) {myEvent += value;}}
remove {lock(myEventLock) {myEvent -= value;}}
}
I could have two threads subscribing at the same time. Thus I wonder if it's
possible one subscription could get lost if I do not lock.
SECOND QUESTION: Do I need to lock when calling the event? Such as:
lock (myEventLock) {if (myEvent!=null) myEvent();}
Or does the C# compiler handle all these details for you. Thanks,
- Fred