UPDATE
从C#6开始,这个问题的答案是:
SomeEvent?.Invoke(this, e);
Run Code Online (Sandbox Code Playgroud)
我经常听到/阅读以下建议:
在检查事件之前,请务必复制事件null并将其触发.这将消除线程的潜在问题,其中事件变为null位于您检查null和触发事件的位置之间的位置:
// Copy the event delegate before checking/calling
EventHandler copy = TheEvent;
if (copy != null)
copy(this, EventArgs.Empty); // Call any handlers on the copied list
Run Code Online (Sandbox Code Playgroud)
更新:我从阅读中了解到这可能还需要事件成员的优化,但Jon Skeet在他的回答中指出CLR不会优化副本.
但同时,为了解决这个问题,另一个线程必须做到这样的事情:
// Better delist from event - don't want our handler called from now on:
otherObject.TheEvent -= OnTheEvent;
// Good, now we can be certain that OnTheEvent will not run...
Run Code Online (Sandbox Code Playgroud)
实际的顺序可能是这种混合物:
// Copy the event delegate before checking/calling
EventHandler copy …Run Code Online (Sandbox Code Playgroud) 我最近一直在使用C#工作,我注意到在我公司的代码中引发事件的大多数代码都是这样完成的:
EventHandler handler = Initialized;
if (handler != null)
{
handler(this, new EventArgs());
}
Run Code Online (Sandbox Code Playgroud)
我真的不明白为什么相反,你不能这样做:
if (Initialized != null)
{
Initialized(this, new EventArgs());
}
Run Code Online (Sandbox Code Playgroud)
编辑:
有些值得深思,我试着对此做一些测试:
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 …Run Code Online (Sandbox Code Playgroud)