Norbert,
Yes, this is what you have to do. However, doing this:
// Check to see if there are any event handlers.
if (ServerQuitMsg != null)
{
// Fire the event.
ServerQuitMsg(. ..);
}
Will cause you to run into problems in an multithreaded environment.
What you want to do really is this:
// Create a temp variable with the list, assuming it is of type
EventHandler.
EventHandler temp = ServerQuitMsg;
// Check to see if there are any event handlers.
if (temp != null)
{
// Fire the events.
temp(...);
}
The reason this is a concern is because another thread could
theoretically remove a delegate from the event list between the check
against null, and the firing of the delegate. Using the code like helps
solve that.
However, this leads to another concern, due to optimizations that the
CLR makes and how it will inline code like this. For most code, it is not a
problem, but it definitely is an issue. There is a detailed explanation for
it in Juval Lowy's book "Programmin g .NET Components, 2nd Edition" by
O'Reilly. You can find the book at Amazon (watch for line wrap):
http://www.amazon.com/exec/obidos/tg...books&n=507846
There is also a good solution in there as well.
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
-
mv*@spam.guard. caspershouse.co m
"nobs" <no**********@g mail.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
Hi guys
I think I missunderstud something with delegates & events
Hopefully someone can bring some light in this issue:
Following problem
I have a class which provide some events
(like ServerQuitMsg)
and in the code i call
(if receivedMsg == QUITMSG)
ServerQuitMsg(. ..);
But If no one ever registerd this Event
ServerQuitMsg == NULL
and I get a NULLPointer Exception
I thought registering for a Event generates a MultiDelegate
and through the += and -= operators I add/remove single Delegates
from the List?
Is this wrong?
How should I handle this problem?
Must I check every call with an if(MyEvent == Null) ???
regards
Norbert