473,554 Members | 3,188 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Unsubscribing from de-referenced object's event?

Do I need to unsubscribe from an object's event before I point the object
variable to a new object?

I have a method that subscribes an event handler to the ListChanged event of
a list. The list is attached to a calendar, so every time a new date is
selected, the list is recreated for the new date. The code then subscribes
the event handler to the new list. Here's the cose (m_ListForSelec tedDay is
a member variable):

private void calendar_DateCh anged(object sender, DateRangeEventA rgs e)
{
// Initialize
DateTime newDate = e.Start;

// Get daily ist for new date
m_ListForSelect edDay = GetDailyList(ne wDate);

// Subscribe to ListChanged event
m_ListForSelect edDay.ListChang ed += new
ListChangedEven tHandler(ListFo rSelectedDay_Li stChanged);
}

Do I need to unsubscribe from the ListChanged event before I point the
ListForSelected Day variable to a new list? If I de-reference the object, but
I still have an event handler subscribed to it, will that keep the object
from being garbage-collected? Thanks in advance.

--
David Veeneman
Foresight Systems
Jan 16 '06 #1
4 1361
"David Veeneman" <da****@nospam. com> wrote in
news:e4******** ******@TK2MSFTN GP11.phx.gbl:
Do I need to unsubscribe from an object's event before I point the
object variable to a new object?


Most definitely. I don't think it will prevent the object from going out
of scope and being GC'ed, but until that happens you might still receive
events from it.

Let me put it this way: its easy to do, and its the right thing to do. So
do it.

-mdb
Jan 16 '06 #2
David Veeneman <da****@nospam. com> wrote:
Do I need to unsubscribe from an object's event before I point the object
variable to a new object?


Well, there are two issues here:

1) Getting an event from the wrong object. If you don't unsubscribe
from the event but the object raises the event, your handler will still
be called.

2) Garbage collection. The "owner" of the event keeps a reference to
the delegates in the event, which (for non-static methods) includes
keeping a reference to the "target" of the delegate. However, there's
no reference the other way. In other words, the owner of the event can
prevent the subscriber from being garbage collected, but not the other
way round.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 16 '06 #3
Me
I agree with ya on that.

A button keeps a reference to the form it is on, but a Form does not keep a
reference to the button.. Well.. it does.. but not from an event stand point
:-)
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
David Veeneman <da****@nospam. com> wrote:
Do I need to unsubscribe from an object's event before I point the object
variable to a new object?


Well, there are two issues here:
2) Garbage collection. The "owner" of the event keeps a reference to
the delegates in the event, which (for non-static methods) includes
keeping a reference to the "target" of the delegate. However, there's
no reference the other way. In other words, the owner of the event can
prevent the subscriber from being garbage collected, but not the other
way round.

Jan 17 '06 #4
Me <me@home.com> wrote:
I agree with ya on that.

A button keeps a reference to the form it is on, but a Form does not keep a
reference to the button.. Well.. it does.. but not from an event stand point
:-)


Well, the button's events keep a reference to whatever the target of
their handlers are - that needn't be a form :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 17 '06 #5

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

Similar topics

2
2675
by: WebRod | last post by:
Bonjour, comment savoir en moins de 5 secondes (enfin rapidement quoi) combien de nouveaux messages non récupérés se trouvent dans une BAL sur une serveur POP3 (pas d'imap donc)???? (en sachant que lorsque l'on récupère les emails, on ne les supprime pas du serveur au fur et à mesure) Parceque OUTLOOK y arrive bien lui!!
0
1722
by: Laurent Pointal | last post by:
Bienvenue sur la liste Python francophone, hébergée par l'AFUL, ou sur le newsgroup fr.comp.lang.python ("fclp"). Votre abonnement à cette liste de diffusion ou votre lecture de fclp montrent un intérêt pour le langage Python et ce qui tourne autour. Après quelques temps de lecture, vous serez sûrement amené à poster vous aussi un...
0
463
by: Michael Dyson | last post by:
M. Michael DYSON DIRECTEUR-ADJOINT SOCIÉTÉ DE SÉCURITÉ SARL. TEL.00229 20 21 80 Cotonou République du Bénin Email:michaeldyson2005@latinmail.com Bonjour . Je sais que mon message sera d’une grande surprise quand t-il vous parviendra. Donc, je vous présente toutes mes excuses. Je vous écris sincèrement dans le but d’obtenir votre...
0
2220
by: Alejandro Scomparin | last post by:
FORMULACION, PREPARACION Y EVALUACION ECONOMICA Y FINANCIERA DE PROYECTOS DE TECNOLOGIA INFORMATICA (IT) en la UTN Inicia: 17 de Mayo. 19 hs Dirigido a Esta preparado para gerentes, jefes, líder de proyectos del área de IT de todo tipo de organizaciones, y para profesionales de
0
4283
by: Alejandro Scomparin | last post by:
FORMULACION, PREPARACION Y EVALUACION ECONOMICA Y FINANCIERA DE PROYECTOS DE TECNOLOGIA INFORMATICA (IT) en la UTN Inicia: 17 de Mayo. 19 hs Dirigido a Esta preparado para gerentes, jefes, líder de proyectos del área de IT de todo tipo de organizaciones, y para profesionales de
4
1180
by: Albert | last post by:
Bye, all: I'm unsubscribing from thiis Usenet group! You guys only talk SHIT Albert
0
1473
by: gandalf | last post by:
Con motivo del enorme esfuerzo realizado para visitar la ciudad argentina de Córdoba, participar en la Reunión del MERCOSUR, en la clausura de la Cumbre de los Pueblos en la histórica Universidad de Córdoba y en la visita a Altagracia, la ciudad donde vivió el Che en su infancia y unido a esto asistir de inmediato a la conmemoración del 53...
1
1614
by: crow | last post by:
http://www.pagina12.com.ar/diario/elpais/1-72984-2006-09-14.html Por Miguel Bonasso Desde La Habana Me había preparado para verlo, pero la realidad fue mucho más fuerte. Incluso le llevaba de regalo un ordenador de viaje. Es decir una suerte de cartuchera de cuero argentino, que en su interior tiene espacios predeterminados para papeles,...
1
1505
by: gandalf | last post by:
CON LA PASION DE SIEMPRE HABLO DE CHAVEZ, DE LA MEDICINA CUBANA... Y DE SU PROPIA MUERTE Relato de la nueva gran batalla de Fidel El líder cubano mostró cómo evoluciona su recuperación en el encuentro con el diputado argentino. También elogió a Hugo Chávez por su lucha para ingresar al Consejo Permanente de la ONU y por aliarse a sectores...
0
7589
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...
0
7787
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. ...
0
7881
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5428
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...
0
3550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3539
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2012
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
1
1121
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
831
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.