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 4 1369
"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
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
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.
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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!!
|
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 message. Voici quelques conseils d'utilisation,
suivi d'une série de liens à partir desquels vous ...
|
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 coopération et votre confiance pouvant
|
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
|
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
| |
by: Albert |
last post by:
Bye, all: I'm unsubscribing from thiis Usenet group!
You guys only talk SHIT
Albert
|
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 aniversario del asalto a los cuarteles Moncada y Carlos Manuel de
Céspedes, el 26 de julio de 1953,...
|
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, tarjetas, pasaje, pasaporte, anotaciones
varias, todo lo que necesita un viajero. Sé muy bien que...
|
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 medios para "hacer los cambios
democráticamente" y mostró su preocupación por terminar de editar
sus...
|
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...
|
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,...
| |
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |