C#提升事件

use*_*875 8 c# events

我最近一直在使用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 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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

不安全版本会导致程序崩溃.

ken*_*n2k 9

第一个版本是尝试使事件成为线程安全的.

请参阅C#事件和线程安全

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

编辑:事件线程安全真的很难实现.看看它的外观 ......如果你实际上并没有处理多个注册/取消注册事件的线程,你就不应该浪费时间来保证线程安全.

  • 嘿......正在努力,但你打败了我:) (2认同)