473,722 Members | 2,468 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Events & Nullpointer Exception

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

Nov 17 '05 #1
3 2205
Yes, you should. Not pretty, but there seems to be no other way.

Nov 17 '05 #2
easiest thing to do is to create a private method to raise the event
that checks then fires it. Makes code look prettier.
Yeah its annoying i agree.

Nov 17 '05 #3
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

Nov 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
2897
by: anonymous.user0 | last post by:
The way I understand it, if I have an object Listener that has registered as a listener for some event Event that's produced by an object Emitter, as long as Emitter is still allocated Listener will stay alive. Is this correct? If this is correct, I've got a problem. Let's say I've got an object Customer that has an PurchaseList (Collection) of Purchase objects. Now, these Purchase objects were pulled from a datasource Datasource. The...
3
6810
by: chramprasad | last post by:
public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { MissionForm missionForm = (MissionForm) form; String strMissionId = InsEncr.getSingleton().decrypt(missionForm.getMissionId().toString()); Long userEntityTypeId = getUserEntityTypeId(request); String strUserEntityTypeId =...
1
1029
by: Nathan | last post by:
I'm currently creating an mdi application and trying to use events between various forms within the app for communication. I have the events working without any problem when all the forms are open but my problem comes when a form that has subscribed to an event is closed and the event handler is not removed. I think I've caused myself problems with the way that I open one form from another, to make things easier the code below is in...
0
2226
by: BigAl.NZ | last post by:
Hi Guys, I am trying to write/copy some code that uses events with a GPS. Everytime the GPS position updates the event fires. The GPS code is from a SDK Library that I got called GPS Tools from www.franson.com For some reason my code below doesnt work - the GpsFixEvent never seems to "fire" as it were.
5
2777
by: Daniel | last post by:
Hey guys When you hook an event (c# 2.0 syntax): myEvent += MyMethodToFire; You need to also unsubscribe it to avoid a resource leak so that the object it is in gets garbage collected like so : myEvent -= MyMethodToFire; That's all fine, but when you use visual studio to create events for objects it never creates an unsubscribing reference, so is it puting in resource leaks? Or is this being cleared somewhere that i am not seeing?
5
3515
by: JasonX | last post by:
Im having problems with my program, in that if I close the main form while my new thread is doing work which involves writing to the main form, then I get an error about a disposed object. To fix this, i have added an event, with the aim the main form subscribes to the event when it is created and unsubscribes as soon as its closed. This approach however has not fixed the problem. When the event is raised, it writes to the form using a...
11
3261
by: MikeT | last post by:
This may sound very elementary, but can you trap when your object is set to null within the object? I have created a class that registers an event from an object passed in the constructor. When my object is destroyed, I want my object to un-register this event. If I don't then the object would never be destroyed until the object I passed in the constructor is destroyed. I have implemented a Dispose(), Dispose(bool), and ~Finalize...
1
1358
by: =?Utf-8?B?U21pdGE=?= | last post by:
I have a gridview, and a listbox which has a different datasource. The listbox contains distinct types of contacts, whereas the gridview will get populated upon contact type selection. The data is displayed but when on submission of the contact type from the list box i get a null reference exception. I already tried to trap using SelectedIndex -1 but that does not work.. Any pointers.
5
1263
by: =?Utf-8?B?QW50?= | last post by:
Hi, I am using a sqlCommand object to run a SP. The SP returns an output parameter that I retrieve the value of, & display. I want to use the StatementCompleted event of the command obj. to handle this output param through the sender object after the command completes. When I try to access this sender object (cast to a command object) & then reference the output parm, I get an error: "Object reference not set to an object"
0
8867
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9386
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9239
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9158
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8059
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6685
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4764
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3208
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2606
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.