473,609 Members | 1,818 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Delegates Subscribe and Unscubscribe

Joe
I have a usercontrol which has an event called NameChanged; The form that
uses the control subscribes to NameChanged.
The first time this form is invoked everything works fine. The second time I
invoke the form it seems theat NameChanged is still holdng a reference to
the first call so that one gets called first and throws an exception about
the object is already disposed.

My question is: Why does the event not get automatically unsubscribed when
the usercontrol is destroyed? Is it required to manually unsubscribe every
event when disposing of an object?
Nov 9 '06 #1
5 1494
Can you be a little clearer about what subscribes to what?

To expand, if object A has an event, and object B subscribes (using an
instance method on B), then A can see B through the event, but not the other
way around.

The usual mistake here is not controls but data entities; e.g. a Customer
object has an event, which a form subscribes to. If that form doesn't
unsubscribe when closing, then the Customer object will actually prevent the
form from being garbage collected. And when the event fires it *will*
attempt to invoke the method on the form, which will usually fail.

In your example you had a control and a form, and I'm guessing that their
lifetime is very similar, so I'm not sure what issue you are seeing. In
particular, it would be unusual for the UserControl to live longer than the
parent Form, so I am confused as to why the event on the UserControl is
causing an issue... unless the UserControl is bound (in turn) to a regular
class as per the previous paragraph.

But the short answer is yes: when an object is cleanly committing suicide it
should unsubscribe from any objects that it reasonably expects to live on
without it - primarily data entities that exist independently of the forms
in an "observer" scenario. Normally child controls don't fall into this
category, as the child control will usually die with the parent. Note that
if you are being finalized (~MyClass) by the GC you shouldn't attempt to do
*anything* with managed references... it could all go horribly wrong.

Marc
Nov 9 '06 #2
Is the event or anything else about the user control static. If the first
form has been disposed then the usercontrol should have fallen out of scope
too, but a new form instance should have a new usercontrol instance on it
anyway.
Look to see if you have static references around the event somewhere
Ciaran O'Donnell
"Joe" wrote:
I have a usercontrol which has an event called NameChanged; The form that
uses the control subscribes to NameChanged.
The first time this form is invoked everything works fine. The second time I
invoke the form it seems theat NameChanged is still holdng a reference to
the first call so that one gets called first and throws an exception about
the object is already disposed.

My question is: Why does the event not get automatically unsubscribed when
the usercontrol is destroyed? Is it required to manually unsubscribe every
event when disposing of an object?
Nov 9 '06 #3
Joe <jb*******@noem ail.noemailwrot e:
I have a usercontrol which has an event called NameChanged; The form that
uses the control subscribes to NameChanged.
The first time this form is invoked everything works fine. The second time I
invoke the form it seems theat NameChanged is still holdng a reference to
the first call so that one gets called first and throws an exception about
the object is already disposed.

My question is: Why does the event not get automatically unsubscribed when
the usercontrol is destroyed? Is it required to manually unsubscribe every
event when disposing of an object?
Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

--
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
Nov 9 '06 #4
Hi Joe,

When the form is shown for the second time, is it a new instance that is
different from the previous instance? Is so, the UserControl on the new
form is a new instance as well. Then the NameChanged event of the new
usercontrol will only hold a reference to the event handler in the new
form, unless the NameChanged event is static.

I performed a test based on your description but didn't produce the
problem. The following is the steps of my test.

1. Create a WindForms application project. Add a UserControl and a form
called From2 in the project.
2. Add a static event to the UserControl. Add a button on the UserControl
to trigger this event.
3. Build the project. Add an instance of the UserControl on Form2 and
subscribe the event of the UserControl in the Form2's constructor.
4. Add a button on Form1. In the button's Click event handler, create a new
instance of Form2 and show it.

Run the program. When I click the button on the Form1 for the first time, a
Form2 appears. I click the button on the Form2 and the event handling
method in the Form2 is executed. Close the Form2. When I click the button
on the Form1 for the second time, a new Form2 instance appears. I click the
button on the new Form2 and the event handling method is executed twice,
which means that the event delegate of the UserControl still holds the
reference to the event handling method in the first Form2 instance. I don't
encounter any exception.

Actually, there's another case that the event receiver is disposed before
the event sender. In this case, when the event is fired, the event delegate
still holds the reference to the event handling method in the event
receiver. For example, there're two forms called Form1 and Form2. Form1 has
an event and Form2 subscribe this event. When the two forms are shown, all
works fine. Now close the Form2 and then trigger the event of Form1. The
event handling method in Form2 is still be executed without any exception.

As for the first case, we should unsubscribe the event of the UserControl
in the form when the form is closed.

As for the second case, we should unsubscribe the event of the Form1 in the
Form2 when the Form2 is closed.

Hope this helps.

If you need our further assistance, please send me your sample project that
could just reproduce the problem. To get the actual email address, remove
'online' from my displayed email address.

Sincerely,
Linda Liu
Microsoft Online Community Support

=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
=============== =============== =============== =====

This posting is provided "AS IS" with no warranties, and confers no rights.

Nov 10 '06 #5
Hi Joe,

How about the problem now?

If the problem has not resolved or you need our further assistance, please
feel free to let me know.

Thank you for using our MSDN Managed Newsgroup Support Service!
Sincerely,
Linda Liu
Microsoft Online Community Support

Nov 14 '06 #6

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

Similar topics

8
7393
by: STom | last post by:
I have a C# Winforms app that has 5 Winforms, lets say A through E. A: Data entry. When data is entered here in any field, values are updated on forms C, D, E.(Not B) B: Data entry form. When data is entered here in any field, values are updated on forms C, D, E (not A). I am considering using delegates to fire events from forms A & B. In forms C, D, E I will have functions with the same signature and even the same name that just...
15
2085
by: Rhy Mednick | last post by:
I have a class (let's call it ClassA) that I've written which has events. In another class (let's call it ClassB) I create a collection of ClassA objects. In a third class (ClassC) I create a reference to some of the ClassA objects created in ClassB. In ClassC I hook into the ClassA events with a foreach loop so that I hook each object. The code is something like this: class ClassC { void SomeMethod() { foreach (ClassA item in...
4
22871
by: LP | last post by:
Hello! I am still transitioning from VB.NET to C#. I undertand the basic concepts of Delegates, more so of Events and somewhat understand AsyncCallback methods. But I need some clarification on when to use one over another? If anyone could provide any additional info, your comments, best practices, any good articles, specific examples, etc. Thank you
2
1119
by: Mirano | last post by:
Hello. I need to implement the publish/subscribe architecture where class B (server) does not have a reference to class A (which is in a client), but class B still has to subscribe to the event raised by the class A. Here's the problem: Class A implements the interface IClient that is on the server, everything's fine. When the method Foo of the class A is executed, the event is raised, passing SomeData as a reference. Now, in order to...
4
5823
by: Tim | last post by:
There are a set of clients who need to be notified of certain events. I have used events and delegates (publisher-Subscriber model) for the notification mechanism. All the clients register with the event publisher and subscribe for the events that they are interested in. When a certain event happens, the subscribers are notified about it. I want the clients to return a value after their callback method is called. If any of the client...
30
3634
by: Burkhard | last post by:
Hi, I am new to C# (with long year experience in C++) and I am a bit confused by the language construct of events. What is it I can do with events that I cannot do with delegates? At the moment it seems to me that Microsoft has developed similar functionality via two keywords. I do understand that an event offers better encapsulation as the underlying delegate is private, but is that all ? -- Regards
11
1872
by: Snowbleach | last post by:
Hello, I am having trouble with the following console application. I am using delegates/event to make a clock raise an alarm when a certain amount of time has been reached. The following compiles, but code does nothing else then to produce an endless loop. Any help would be greatly appreciated, I'm probably overlooking something silly. Regards, Arjen.
1
1869
by: Bruce Wood | last post by:
I'm trying to "genericize" the following class. At the moment I have derived classes for each different type of event handler / event arguments, and I wanted to have a single, generic, catch-all class for wrapping an event subscription in a "weak" event handler. Unfortunately, I've been bitten by the restriction that one can't do this: public class Blah<T: WeakReference where T : Delegate
5
2391
by: raylopez99 | last post by:
I understand delegates (static and non-static) and I agree they are very useful, and that the "Forms" used in the Windows .NET API could not work without them. That said, I'm curious as to how many heavy duty pro programmers in this newsgroup have actually used a delegate in their code, say in the last year of coding. By "use" I mean constructed a delegate and using it in an Event Source class and an Event Receiver class. Interfaces...
0
8133
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
8083
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8573
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...
1
8224
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,...
1
6062
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
5517
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();...
0
4026
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...
1
2535
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
0
1393
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.