I've been working a lot with C# recently, and I've noticed that most code that raises events in my company's code is done like this:
EventHandler handler = Initialized;
if (handler != null)
{
handler(this, new EventArgs());
}
I really don't understand why, instead, you can't do just do that:
if (Initialized != null)
{
Initialized(this, new EventArgs());
}
EDIT:
Some food for thought, I tried doing a few tests on this:
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);
}
}
}
}
The Unsafe version makes the program crash.
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
The first version is an attempt to make the event thread-safe.
See C# Events and Thread Safety
Actually, as said in the discussion, it doesn't make the event thread safe. Thus I would use the second version that is shorter instead.
EDIT: event thread-safety is really hard to implement. Look at what it might look... If you're not actually dealing with multiple threads that register/unregister events, you shouldn't waste time with thread-safety.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With