简体   繁体   中英

How to Explicit event accessors

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 

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;} 
    }
 }
  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM