В последнее время я много работал с C # и заметил, что большая часть кода, который вызывает события в коде моей компании, делается так:
EventHandler handler = Initialized;
if (handler != null)
{
handler(this, new EventArgs());
}
Я действительно не понимаю, почему вместо этого вы не можете просто сделать это:
if (Initialized != null)
{
Initialized(this, new EventArgs());
}
EDIT:
Пища для размышлений, я попытался сделать несколько тестов на этом:
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);
}
}
}
}
Небезопасная версия вызывает сбой программы.