On the MSDN, I have found following:
public event EventHandler<MyEventArgs> SampleEvent;
public void DemoEvent(string val)
{
// Copy to a temporary variable to be thread-safe.
EventHandler<MyEventArgs> temp = SampleEvent;
Is it reference?
If so I do not understand its meaning as when SampleEvent became null, so does the temp
if (temp != null)
temp(this, new MyEventArgs(val));
}
Main difference between value type and reference type is value type copy a data while reference types share a single copy of their data. Value Type immutable its mean when we create a instance with a value type its create a unique copy of data and it can't change but reference type is mutable its value can be change ..
There are two kinds of types in Visual Basic: reference types and value types. Variables of reference types store references to their data (objects), while variables of value types directly contain their data.
All fundamental data types, Boolean, Date, structs, and enums are examples of value types. Examples of reference types include: strings, arrays, objects of classes, etc. To create reference types in C#, you can take advantage of these keywords: class, interface and delegate.
Structs are value types, while classes are reference types, and the runtime deals with the two in different ways. When a value-type instance is created, a single space in memory is allocated to store the value. Primitive types such as int, float, bool and char are also value types, and work in the same way.
This is a paranoia thing to do with threading. If another thread unsubscribes the last handler just after you've checked it for null
, it could become null
and you'll cause an exception. Since delegates are immutable, capturing a snapshot of the delegate into a variable stops this from happening.
Of course, it does have the other side effect that you could (instead) end up raising the event against an object that thinks it already unsubscribed...
But to stress - this is only an issue when multiple threads are subscribing / unsubscribing to the object, which is a: rare, and b: not exactly desirable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With