ho lavorato molto con C# di recente, e ho notato che la maggior parte del codice che genera eventi nel codice della mia azienda è fatto in questo modo:C alzando # eventi
EventHandler handler = Initialized;
if (handler != null)
{
handler(this, new EventArgs());
}
Io davvero non capisco il motivo per cui, invece, non si può fare proprio farlo:
if (Initialized != null)
{
Initialized(this, new EventArgs());
}
EDIT:
alcuni spunti di riflessione, ho provato a fare alcuni test su questo:
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);
}
}
}
}
La versione Unsafe fa arrestare il programma.
Immagino sia necessario chiedere alle persone che hanno scritto il codice originale. –
Vedi http://blogs.msdn.com/b/ericlippert/archive/2009/04/29/events-and-races.aspx –
Ottimo articolo Eric, grazie! – user472875