C#引发事件

标签 c# 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);
            }
        }
    }
}

Unsafe版本导致程序崩溃。

最佳答案

第一个版本试图使事件线程安全

参见 C# Events and Thread Safety

实际上,正如讨论中所说,它不会使事件线程安全。因此,我会使用更短的第二个版本。

编辑:事件线程安全真的很难实现。看what it might look ...如果您实际上没有处理注册/取消注册事件的多个线程,那么您不应该在线程安全上浪费时间。

关于C#引发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9330252/

相关文章:

c# - 通过 SOCKET 发送文件

c# - 我应该*总是*同步访问从多个线程使用的所有双字段/属性/变量吗?

c# - 如何将模板对象添加到 C# Frame 模板中

c# - lambda 事件处理程序会导致什么样的内存泄漏?

javascript - 包裹在单选按钮周围的标签标记会阻止单选按钮响应 JavaScript 中的 "change"事件监听器

python - celery :事件==信号?

c# - 为什么 EndGetResponse 抛出 ArgumentNullException?

c# - DataType(DataType.*) 的用途是什么?

events - 如何在 Svelte 组件安装之前获取数据?

javascript - 为什么 onpropertychange 对我不起作用?