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.
c # events
user472875
source share