Reputation: 6531
Here is a sketch of explicit event assessors:
delegate void EventHandler (SomeObject m, EventArgs e);
EventHandler _priceChanged; //Private Delegate
public event EventHandler PriceChanged
{
add {_priceChanged += value;}
remove {_priceChanged -= value;}
}
Apparently the difference between this and the standard implementation is that the use of the delegate is not thread-safe. How do I make this thread-safe?
How do I allow things like :
if (PriceChanged != null)... etc
Upvotes: 0
Views: 1339
Reputation: 5402
- Apparently the difference between this and the standard implementation is that the use of the delegate is not thread-safe. How do I make this thread-safe?
Refer to Shai's answer.
- How do I allow things like :
if (PriceChanged != null)... etc
You can't, not on the eventhandler declaration level - this always needs to be done in the code calling this.
Just to give an example: one reason for _priceChanged
to be null is if neither add nor remove was ever called - how could they prevent the null exception then? Unless you want to initialize your delegate collection with a dummy callback, but that's just evil.
Have a look at reactive extensions if you want an alternative.
Upvotes: 1
Reputation: 1957
Try this:
delegate void EventHandler (SomeObject m, EventArgs e);
EventHandler _priceChanged; //Private Delegate
private Object _myLock = new Object();
public event EventHandler PriceChanged
{
add {
lock(_myLock)
{_priceChanged += value;}
}
remove {
lock(_myLock)
{_priceChanged -= value;}
}
}
Upvotes: 1