[英]C# raising events
我最近一直在使用C#工作,我注意到在我公司的代码中引发事件的大多数代码都是这样完成的:
EventHandler handler = Initialized;
if (handler != null)
{
handler(this, new EventArgs());
}
我真的不明白为什么相反,你不能这样做:
if (Initialized != null)
{
Initialized(this, new EventArgs());
}
编辑:
有些值得深思,我试着对此做一些测试:
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);
}
}
}
}
不安全版本会导致程序崩溃。
第二个版本不是线程安全的。
if (Initialized != null)
{
Initialized(this, new EventArgs());
}
如果最后一个处理程序在if (Initialized != null)
之后取消订阅,那么最终会出现null ref异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.