事件处理程序/引发程序代码段

| 我想听听对以下代码段的意见。有什么可以改善的吗?事件处理程序/引发程序是否遵循最佳做法命名?我知道在同一个类中处理和引发事件不是很有用,但这只是一小段。
public class MyControl
{
    public MyControl()
    {
        this.LogWritten += this.HandleMyControlLogWritten;
    }

    // Event handler
    void HandleMyControlLogWritten(object sender, EventArgs e)
    {
    }

    // Event object
    public event Action<object, EventArgs> LogWritten;

    // Event raiser
    protected virtual void OnLogWritten(EventArgs e)
    {
        if (this.LogWritten != null)
        {
            this.LogWritten(this, e);
        }
    }
}
    
已邀请:
        我建议的主要更改是获取事件处理程序的副本:
// Event raiser
protected virtual void OnLogWritten(EventArgs e)
{
    var handler = this.LogWritten;
    if (handler != null)
    {
        handler(this, e);
    }
}
如果您打算(最终)在多线程方案中使用此类,则这一点很重要。因此,我发现养成使用习惯是一个很好的“最佳实践”。问题是,在多个线程中使用时,如果不创建副本,则可能只有附加的“处理程序”可能在空检查和调用之间退订,这将导致运行时错误。通过复制到临时变量(“ѭ2”)行,您正在有效地创建订户列表的“快照”,然后检查它是否为null并在需要时调用。 另一个更改是事件声明本身。代替使用
Action<T1,T2>
// Event object
public event Action<object, EventArgs> LogWritten;
我建议使用
EventHandler<TEventArgs>
(如果要使用自定义
EventArgs
子类)或
EventHandler
(对于标准
EventArgs
)。这些是更多的“标准做法”,并且将是其他开发人员所期望的:
// Event object
public event EventHandler LogWritten;
    

要回复问题请先登录注册