EventHandler<TEventArgs> thread safety in C#?

Viewed 1014

Using my cusom EventArgs such as :

public event EventHandler<MyEventArgs> SampleEvent;

from msdn e.g :

public class HasEvent
{
// Declare an event of delegate type EventHandler of 
// MyEventArgs.

    public event EventHandler<MyEventArgs> SampleEvent;

    public void DemoEvent(string val)
    {
    // Copy to a temporary variable to be thread-safe.
        EventHandler<MyEventArgs> temp = SampleEvent;
        if (temp != null)
            temp(this, new MyEventArgs(val));
    }
}

I have 2 questions:

1) looking at the marked code :

enter image description here

I don't see a reason why it should be copied to another param ( regarding threads)

since we have the event keyowrd , no one can touch its invocation list ( no outsider code to the class I mean)

2) If I'm not mistaken, the DemoEvent function should be virtual, so it can be overridden in sub classes... (I'm sure I've seen it somewhere)

the strange thing is that resharper also won't add virtual :

so if I have this code:

enter image description here

it suggests me :

enter image description here

and when I press it :

enter image description here

so again my 2 questions :

1) What is the scenario which this line EventHandler<MyEventArgs> temp = SampleEvent; will solve , regarding thread safty?

2) Shouldn't the function be virtual? ( I'm sure I've seen this pattern with virtual)

2 Answers
Related