Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question regarding to value/reference type of events

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));
}
like image 661
Petr Avatar asked Apr 08 '10 07:04

Petr


People also ask

How do you compare value types and reference types?

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 ..

What is the main difference between a value type and a reference type?

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.

What is the difference between a value type and a reference type give an example of each type?

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.

Why class is reference type and structure is value type?

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.


1 Answers

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.

like image 84
Marc Gravell Avatar answered Oct 25 '22 01:10

Marc Gravell