C # Raising Activities

I recently worked a lot with C #, and I noticed that most of the code that raises events in my corporate code runs as follows:

EventHandler handler = Initialized; if (handler != null) { handler(this, new EventArgs()); } 

I really don't understand why you cannot do this instead:

 if (Initialized != null) { Initialized(this, new EventArgs()); } 

EDIT:

Some food for thought, I tried to do some tests about this:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Test t = new Test(true); while(true) { t.Ev += new EventHandler(t_Ev); t.Ev -= new EventHandler(t_Ev); } } static void t_Ev(object sender, EventArgs e) { } } public class Test { private readonly bool m_safe; public Test(bool safe) { m_safe = safe; Thread t = new Thread(Go); t.Start(); } private void Go() { while (true) { if(m_safe) { RaiseSafe(); } else { RaiseUnsafe(); } } } public event EventHandler Ev; public void RaiseUnsafe() { if(Ev != null) { Ev(this, EventArgs.Empty); } } public void RaiseSafe() { EventHandler del = Ev; if (del != null) { del(this, EventArgs.Empty); } } } } 

An unsafe version causes the program to crash.

+8
c # events
source share
2 answers

The first version is an attempt to make the thread thread safe .

See C # Events and Thread Safety

Actually, as stated in the discussion, this does not make the event flow safe. So I would use the second version, which is shorter.

EDIT: Security of the event flow is really complex. Look at what he can see ... If you really are not dealing with multiple threads that register / unregister events, you should not waste time on thread safety.

+9
source share

The second version is not thread safe.

 if (Initialized != null) { Initialized(this, new EventArgs()); } 

If the last handler does not sign after if (Initialized != null) , then you will get a null ref exception.

0
source share

All Articles