我最近一直在使用 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);
}
}
}
}
Unsafe版本导致程序崩溃。
最佳答案
第一个版本试图使事件线程安全。
参见 C# Events and Thread Safety
实际上,正如讨论中所说,它不会使事件线程安全。因此,我会使用更短的第二个版本。
编辑:事件线程安全真的很难实现。看what it might look ...如果您实际上没有处理注册/取消注册事件的多个线程,那么您不应该在线程安全上浪费时间。
关于C#引发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9330252/