C#筹款活动

C#筹款活动,c#,events,C#,Events,我最近在C#上做了很多工作,我注意到在我公司的代码中引发事件的大多数代码都是这样做的: EventHandler handler = Initialized; if (handler != null) { handler(this, new EventArgs()); } 我真的不明白为什么你不能这么做: if (Initialized != null) { Initialized(this, new EventArgs()); } 编辑: 值得思考的是,我试着做了一些测试

我最近在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);
            }
        }
    }
}

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

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

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


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

第二个版本不是线程安全的

if (Initialized != null)
{
    Initialized(this, new EventArgs());
}

如果最后一个处理程序在
If(Initialized!=null)
之后取消订阅,那么您将遇到null ref异常。

我想您需要询问编写原始代码的人员。请参阅heh。。。我正试图这么做,但你抢先一步:)实际上,这两个版本都不是线程安全的,这取决于你对线程安全的定义。当然,您可以避免空的取消引用,但是第一个版本不能避免潜在地调用已在另一个线程上删除的处理程序。