473,728 Members | 1,713 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

When objects are set to null...removing events

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 method,
where the finalize calls Dispose. But this is only called when the
object is Garbage Collected.

If the developer using my object uses one of the following statements,
I want my object to unregister the event:

myObject = null;

or

myObject = new myObject()

Is this possible? If not, can I force the developer to call the
Dispose method?

I imagine other have run into this scenario, what have you done?

Thanks to anyone that can help.

Apr 25 '07 #1
11 3261
The expression "myObject = null" refs myObject to null reference (not
refer to any object) and GC will collect it by the next iteration. If
developer determinates an object as IDisposable he should use the
"using" statement
(http://msdn2.microsoft.com/en-us/library/yh598w02.aspx)

By the way u should provide the "GC.SuppressFin alize(this)" in the
..Dispose method to suppress unnecessary Finalize call.

Regards, Alex Meleta
Blog:: http://devkids.blogspot.com
-----Original Message-----
From: MikeT [mailto:th****** ****@gmail.com]
Posted At: Wednesday, April 25, 2007 3:36 PM
Posted To: microsoft.publi c.dotnet.langua ges.csharp
Conversation: When objects are set to null...removing events
Subject: When objects are set to null...removing events

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 method,
where the finalize calls Dispose. But this is only called when the
object is Garbage Collected.

If the developer using my object uses one of the following statements,
I want my object to unregister the event:

myObject = null;

or

myObject = new myObject()

Is this possible? If not, can I force the developer to call the
Dispose method?

I imagine other have run into this scenario, what have you done?

Thanks to anyone that can help.

Apr 25 '07 #2
MikeT wrote:
This may sound very elementary, but can you trap when your object is
set to null within the object?
You cannot.
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.
The idiomatic way to implement this semantic in .NET is to implement
IDisposable, but it also requires that the users of your class play
along, by calling Dispose() as necessary, or alternatively using
instances of your class only in 'using' blocks.
I have implemented a Dispose(), Dispose(bool), and ~Finalize method,
where the finalize calls Dispose. But this is only called when the
object is Garbage Collected.
Finalizers are for very limited scenarios, such as wrapping unmanaged
resources. Unless you're interacting with the OS or a native library at
a very low level, you don't ever need to implement a finalizer.

You should implement IDisposable on your class; this involves having a
Dispose() method. The Dispose() method should call your protected
virtual Dispose(bool) method passing along 'true', and you should
unregister your event handler in the Dispose(bool) method roughly like
this:

---8<---
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
someOtherObject .TheEvent -= MyHandler;
}
}
--->8---

If there were such a thing as weak delegates in .NET, what your after
would be somewhat more possible, but it would still be non-deterministic
due to GC.
If the developer using my object uses one of the following statements,
I want my object to unregister the event:

myObject = null;

or

myObject = new myObject()

Is this possible?
No.
If not, can I force the developer to call the
Dispose method?
No.
I imagine other have run into this scenario, what have you done?
Always dispose objects that implement IDisposable, and implement
IDisposable on objects which need disposing.

-- Barry

--
http://barrkel.blogspot.com/
Apr 25 '07 #3
Alex Meleta wrote:
The expression "myObject = null" refs myObject to null reference (not
refer to any object) and GC will collect it by the next iteration.
It won't, because the OP has subscribed for an event. The delegate
instance in the event handler will keep the object alive, preventing
collection.

-- Barry

--
http://barrkel.blogspot.com/
Apr 25 '07 #4
On Apr 25, 5:29 am, Barry Kelly <barry.j.ke...@ gmail.comwrote:
MikeT wrote:
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 there were such a thing as weak delegates in .NET, what your after
would be somewhat more possible, but it would still be non-deterministic
due to GC.
This is another way to handle the problem. You can, in fact, build
weak event subscriber placeholders and use them to subscribe to
events. From the point of view of your object (the real subscriber)
the event subscription then "doesn't count" so far as garbage
collection is concerned: your object will be GC'd when the last
pointer to it goes out of scope, despite the event subscription.

The next time the event is raised, the tiny placeholder object, which
is still subscribed to the event, will detect that its target (to
which it holds a weak reference) is gone, and will unsubscribe itself.

So yes... it can be done. You just have to write it yourself. :-)

I have some .NET 1.1 sample code at work... I can post it. You're
better off changing it to use generics, though. Then you get a general-
purpose wrapper that you can use for weak subscription to any event.

Apr 26 '07 #5
This is another way to handle the problem. You can, in fact, build
weak event subscriber placeholders and use them to subscribe to
events. From the point of view of your object (the real subscriber)
the event subscription then "doesn't count" so far as garbage
collection is concerned: your object will be GC'd when the last
pointer to it goes out of scope, despite the event subscription.

The next time the event is raised, the tiny placeholder object, which
is still subscribed to the event, will detect that its target (to
which it holds a weak reference) is gone, and will unsubscribe itself.
This is an interesting concept. I would like to see some sample code,
so if you can post that would be great.

All the other comments that have been posted is what I expected. In
this particular project, my objects are used by other developers
within my company. However, most of them are new to .Net development
(ex-Powerbuilder), so I'm trying to prevent them from making a costly
mistake, such as not calling Dispose every time.
>
So yes... it can be done. You just have to write it yourself. :-)

Apr 26 '07 #6
On Apr 26, 7:09 am, MikeT <therien.m...@g mail.comwrote:
This is another way to handle the problem. You can, in fact, build
weak event subscriber placeholders and use them to subscribe to
events. From the point of view of your object (the real subscriber)
the event subscription then "doesn't count" so far as garbage
collection is concerned: your object will be GC'd when the last
pointer to it goes out of scope, despite the event subscription.
The next time the event is raised, the tiny placeholder object, which
is still subscribed to the event, will detect that its target (to
which it holds a weak reference) is gone, and will unsubscribe itself.

This is an interesting concept. I would like to see some sample code,
so if you can post that would be great.

All the other comments that have been posted is what I expected. In
this particular project, my objects are used by other developers
within my company. However, most of them are new to .Net development
(ex-Powerbuilder), so I'm trying to prevent them from making a costly
mistake, such as not calling Dispose every time.
Here are my two basic classes for weak delegates. I can post some code
that uses them, later.

Sorry about the line wrapping and such. I tried to find one of those
free "paste buffer" sites on the Web, but couldn't track one down in
short order, so I'm posting here. If you know of one, I can post the
code there, which will make it more readable.
#region WeakEventRefere nce

/// <summary>
/// Used to subscribe to <em>static</emevents
/// when the subscriber wants to subscribe via a weak reference
rather than a strong
/// reference.
/// </summary>
/// <remarks>Subscr ibing via a weak reference allows event
subscribers to be
/// garbage collected without having to unsubscribe to the event,
but it also
/// comes with a host of concurrency considerations, not the least
of which
/// is that the event handler method on the subscriber could be
called and be
/// executing while the object is being garbage collected!
/// <para>Subscribi ng via weak references is usually done when
subscribing to
/// static events, since the event supplier will never be garbage
collected,
/// and so anything to which it holds strong references (regular
event
/// subscriptions) will never be garbage collected.</para>
/// </remarks>
public abstract class WeakEventRefere nce : WeakReference
{
private EventInfo _provider;
private MethodInfo _subscriberMeth od;

/// <summary>
/// Creates a new weak reference wrapper for an event handler.
/// </summary>
/// <param name="subscribe r">The object that wishes to subscribe
/// to the provider event.</param>
/// <param name="subscribe rMethod">The method that should be
called
/// whenever the event is raised.</param>
/// <param name="provider" >The event to which the subscriber is
subscribing. It is still
/// the caller's responsibility to subscribe to the event. This
event information
/// is used to unsubscribe from the event after the subscriber has
been garbage
/// collected.</param>
/// <param name="eventArgu mentType">The type of event arguments
that
/// <paramref name="subscribe rMethod"/should accept as its
second
/// argument.</param>
/// <param name="eventHand lerType">The type of event handler that
/// <paramref name="provider"/should be expecting as a
subscriber.
/// </param>
/// <exception cref="ArgumentE xception"><para mref
name="subscribe rMethod"/>
/// does not accept two arguments: System.Object and
/// <paramref name="eventArgu mentType"/>, or
/// <paramref name="provider"/does not allow event handlers
/// of type <paramref name="eventHand lerType"/to subscribe
/// to it.</exception>
/// <remarks>The caller should subscribe the <c>MyEventHandl er</c>
method to the event
/// <c>StaticEven t</clike this:
/// <code>
/// EventProviderTy pe.StaticEvent += new
ItemAddingWeakR eference(this, this.GetType(). GetMethod("Item Added"),
///
typeof(EventPro viderType).GetE vent("StaticEve nt")).Delegat e;
/// </code>
/// </remarks>
protected WeakEventRefere nce(object subscriber, MethodInfo
subscriberMetho d, EventInfo provider, Type eventArgumentTy pe, Type
eventHandlerTyp e) : base(subscriber )
{
if (subscriber == null)
{
throw new ArgumentNullExc eption("subscri ber");
}
if (subscriberMeth od == null)
{
throw new ArgumentNullExc eption("subscri berMethod");
}
if (!
subscriberMetho d.DeclaringType .IsAssignableFr om(subscriber.G etType()))
{
throw new ArgumentExcepti on(String.Forma t("Cannot subscribe an
object of type {0} to a method with declaring type {1} because the
types are not compatible.", subscriber.GetT ype(),
subscriberMetho d.DeclaringType ), "subscriber ");
}
this._subscribe rMethod = subscriberMetho d;
ParameterInfo[] subscriberMetho dParameters =
subscriberMetho d.GetParameters ();
if (subscriberMeth odParameters.Le ngth != 2)
{
throw new ArgumentExcepti on(String.Forma t("The method
subscribing to the event takes {0} parameters, not the required two
parameters (object, {1}).", subscriberMetho dParameters.Len gth,
eventArgumentTy pe), "subscriberMeth od");
}
else if (!
subscriberMetho dParameters[0].ParameterType. Equals(typeof(o bject)))
{
throw new ArgumentExcepti on(String.Forma t("The method
subscribing to the event has its second parameter of type {0}, not the
required parameter type System.Object." ,
subscriberMetho dParameters[0]), "subscriberMeth od");
}
else if (!
subscriberMetho dParameters[1].ParameterType. Equals(eventArg umentType))
{
throw new ArgumentExcepti on(String.Forma t("The method
subscribing to the event has its second parameter of type {0}, not the
required parameter type {1}.", subscriberMetho dParameters[1],
eventArgumentTy pe), "subscriberMeth od");
}
this._provider = provider;
if (!this._provide r.EventHandlerT ype.Equals(even tHandlerType))
{
throw new ArgumentExcepti on(String.Forma t("EventInfo is for a
{0} event handler, not a {1}", this._provider. EventHandlerTyp e,
eventHandlerTyp e), "provider") ;
}
}

/// <summary>
/// Creates a new weak reference wrapper for an event handler.
/// </summary>
/// <param name="subscribe r">The object that wishes to subscribe
/// to the provider event.</param>
/// <param name="subscribe rType">The type of the subscriber. This
is passed explicitly
/// so to search for the <paramref name="subscribe rMethod"/at
the correct
/// level of the class hierarchy, since <paramref
name="subscribe r"/may be
/// a sub-class of <paramref name="subscribe rType"/>.</param>
/// <param name="subscribe rMethod">The method that should be
called
/// whenever the event is raised.</param>
/// <param name="providerT ype">The static type that defines the
event
/// to which the subscriber is subscribing.</param>
/// <param name="providerE vent">The name of the event to which the
subscriber is subscribing. It is still
/// the caller's responsibility to subscribe to the event. This
event information
/// is used to unsubscribe from the event after the subscriber has
been garbage
/// collected.</param>
/// <param name="eventArgu mentType">The type of event arguments
that
/// <paramref name="subscribe rMethod"/should accept as its
second
/// argument.</param>
/// <param name="eventHand lerType">The type of event handler that
/// <paramref name="providerE vent"/should be expecting as a
subscriber.
/// </param>
/// <exception cref="MissingMe thodException">
/// <paramref name="subscribe rType"/does not declare a method
/// called <paramref name="subscribe rMethod"/>.</exception>
/// <exception cref="MissingMe mberException">
/// <paramref name="providerT ype"/does not declare a static
event
/// called <paramref name="providerE vent"/>.</exception>
/// <exception cref="ArgumentE xception"><para mref
name="subscribe rMethod"/>
/// does not accept two arguments: System.Object and
/// <paramref name="eventArgu mentType"/>, or
/// <paramref name="providerE vent"/does not allow event handlers
/// of type <paramref name="eventHand lerType"/to subscribe
/// to it.</exception>
/// <remarks>The caller should subscribe the <c>MyEventHandl er</c>
method to the event
/// <c>StaticEven t</clike this:
/// <code>
/// EventProviderTy pe.StaticEvent += new
ItemAddingWeakR eference(this, this, "ItemAdded" ,
typeof(EventPro viderType), "StaticEvent"). Delegate;
/// </code>
/// </remarks>
protected WeakEventRefere nce(object subscriber, Type
subscriberType, string subscriberMetho d, Type providerType, string
providerEvent, Type eventArgumentTy pe, Type eventHandlerTyp e) :
base(subscriber )
{
if (subscriber == null)
{
throw new ArgumentNullExc eption("subscri ber");
}
if (subscriberType == null)
{
throw new ArgumentNullExc eption("subscri berType");
}
if (subscriberMeth od == null)
{
throw new ArgumentNullExc eption("subscri berMethod");
}
if (!subscriberTyp e.IsAssignableF rom(subscriber. GetType()))
{
throw new ArgumentExcepti on(String.Forma t("Cannot subscribe an
object of type {0} to a method with declaring type {1} because the
types are not compatible.", subscriber.GetT ype(), subscriberType) ,
"subscriber ");
}
this._subscribe rMethod =
subscriberType. GetMethod(subsc riberMethod, BindingFlags.In stance |
BindingFlags.No nPublic | BindingFlags.Pu blic);
if (this._subscrib erMethod == null)
{
throw new MissingMethodEx ception(String. Format("Subscri ber of
type '{0}' does not have an event handler method called '{1}'.",
subscriber.GetT ype(), subscriberMetho d));
}
ParameterInfo[] subscriberMetho dParameters =
this._subscribe rMethod.GetPara meters();
if (subscriberMeth odParameters.Le ngth != 2)
{
throw new ArgumentExcepti on(String.Forma t("The method
subscribing to the event takes {0} parameters, not the required two
parameters (object, {1}).", subscriberMetho dParameters.Len gth,
eventArgumentTy pe), "subscriberMeth od");
}
else if (!
subscriberMetho dParameters[0].ParameterType. Equals(typeof(o bject)))
{
throw new ArgumentExcepti on(String.Forma t("The method
subscribing to the event has its second parameter of type {0}, not the
required parameter type System.Object." ,
subscriberMetho dParameters[0]), "subscriberMeth od");
}
else if (!
subscriberMetho dParameters[1].ParameterType. Equals(eventArg umentType))
{
throw new ArgumentExcepti on(String.Forma t("The method
subscribing to the event has its second parameter of type {0}, not the
required parameter type {1}.", subscriberMetho dParameters[1],
eventArgumentTy pe), "subscriberMeth od");
}
if (providerType == null)
{
this._provider = null;
}
else
{
if (providerEvent == null)
{
throw new ArgumentNullExc eption("provide rEvent");
}
this._provider = providerType.Ge tEvent(provider Event);
if (this._provider == null)
{
throw new MissingMemberEx ception(String. Format("Provide r
type '{0}' does not publish a static event called '{1}'",
providerType, providerEvent)) ;
}
if (!this._provide r.EventHandlerT ype.Equals(even tHandlerType))
{
throw new ArgumentExcepti on(String.Forma t("Event provider
event is for a {0}, not a {1}", this._provider. EventHandlerTyp e,
eventHandlerTyp e), "providerEvent" );
}
}
}

/// <summary>
/// Gets the event provider for the event to which the weak
/// reference delegate has subscribed.
/// </summary>
/// <value>Informat ion about the event to which this weak
/// reference is subscribing.</value>
protected EventInfo Provider
{
get { return this._provider; }
}

/// <summary>
/// Gets the method information for the method to call on the
/// event subscriber.
/// </summary>
/// <value>Informat ion about the method that this weak reference
/// is to call each time the event occurs.</value>
protected MethodInfo SubscriberMetho d
{
get { return this._subscribe rMethod; }
}
}

#endregion

#region SystemEventWeak Reference

/// <summary>
/// Used to subscribe to static events that require <see
cref="System.Ev entHandler"/>,
/// when the subscriber wants to subscribe via a weak reference
rather than a strong
/// reference.
/// </summary>
/// <remarks>Subscr ibing via a weak reference allows event
subscribers to be
/// garbage collected without having to unsubscribe to the event,
but it also
/// comes with a host of concurrency considerations, not the least
of which
/// is that the event handler method on the subscriber could be
called and be
/// executing while the object is being garbage collected!
/// <para>Subscribi ng via weak references is usually done when
subscribing to
/// static events, since the event supplier will never be garbage
collected,
/// and so anything to which it holds strong references (regular
event
/// subscriptions) will never be garbage collected.</para>
/// </remarks>
public class SystemEventWeak Reference : WeakEventRefere nce
{
/// <summary>
/// Creates a new weak reference wrapper for an event handler.
/// </summary>
/// <param name="subscribe r">The object that wishes to subscribe
/// to the provider event.</param>
/// <param name="subscribe rMethod">The method that should be
called
/// whenever the event is raised.</param>
/// <param name="provider" >The event to which the subscriber is
subscribing. It is still
/// the caller's responsibility to subscribe to the event. This
event information
/// is used to unsubscribe from the event after the subscriber has
been garbage
/// collected.</param>
/// <remarks>The caller should subscribe the <c>MyEventHandl er</c>
method to the event
/// <c>StaticEven t</clike this:
/// <code>
/// EventProviderTy pe.StaticEvent += new
SystemEventWeak Reference(this,
this.GetType(). GetMethod("MyEv entHandler"),
///
typeof(EventPro viderType).GetE vent("StaticEve nt")).Delegat e;
/// </code>
/// </remarks>
public SystemEventWeak Reference(objec t subscriber, MethodInfo
subscriberMetho d, EventInfo provider) :
base(subscriber , subscriberMetho d, provider,
typeof(System.E ventArgs), typeof(System.E ventHandler))
{ }

/// <summary>
/// Creates a new weak reference wrapper for an event handler.
/// </summary>
/// <param name="subscribe r">The object that wishes to subscribe
/// to the provider event.</param>
/// <param name="subscribe rType">The type of the subscriber. This
is passed explicitly
/// so to search for the <paramref name="subscribe rMethod"/at
the correct
/// level of the class hierarchy, since <paramref
name="subscribe r"/may be
/// a sub-class of <paramref name="subscribe rType"/>.</param>
/// <param name="subscribe rMethod">The method that should be
called
/// whenever the event is raised.</param>
/// <param name="providerT ype">The static type that defines the
event
/// to which the subscriber is subscribing.</param>
/// <param name="providerE vent">The name of the event to which the
subscriber is subscribing. It is still
/// the caller's responsibility to subscribe to the event. This
event information
/// is used to unsubscribe from the event after the subscriber has
been garbage
/// collected.</param>
/// <remarks>The caller should subscribe the <c>MyEventHandl er</c>
method to the event
/// <c>StaticEven t</clike this:
/// <code>
/// EventProviderTy pe.StaticEvent += new
SystemEventWeak Reference(this, this, "MyEventHandler ",
typeof(EventPro viderType), "StaticEvent"). Delegate;
/// </code>
/// </remarks>
public SystemEventWeak Reference(objec t subscriber, Type
subscriberType, string subscriberMetho d, Type providerType, string
providerEvent) :
base(subscriber , subscriberType, subscriberMetho d, providerType,
providerEvent, typeof(System.E ventArgs), typeof(System.E ventHandler))
{ }

/// <summary>
/// Creates a new weak reference wrapper for an event handler.
/// </summary>
/// <param name="subscribe r">The object that wishes to subscribe
/// to the provider event.</param>
/// <param name="subscribe rMethod">The method that should be
called
/// whenever the event is raised.</param>
/// <remarks>The caller should subscribe the <c>MyEventHandl er</c>
method to the event
/// <c>StaticEven t</clike this:
/// <code>
/// EventProviderTy pe.StaticEvent += new
SystemEventWeak Reference(this,
this.GetType(). GetMethod("MyEv entHandler")).D elegate;
/// </code>
/// Note that using this constructor does not allow the weak
reference wrapper to
/// unsubscribe from the event if its target is garbage collected,
and so the (admittedly tiny)
/// weak reference wrappers will build up in memory and event
delegate chains will get
/// longer and longer, cluttered with "dead" weak references.
Nonetheless, for small
/// applications where this may not matter, this constructor
offers a simpler calling sequence.
/// </remarks>
public SystemEventWeak Reference(objec t subscriber, MethodInfo
subscriberMetho d) : this(subscriber , subscriberMetho d, null)
{ }

/// <summary>
/// Creates a new weak reference wrapper for an event handler.
/// </summary>
/// <param name="subscribe r">The object that wishes to subscribe
/// to the provider event.</param>
/// <param name="subscribe rType">The type of the subscriber. This
is passed explicitly
/// so to search for the <paramref name="subscribe rMethod"/at
the correct
/// level of the class hierarchy, since <paramref
name="subscribe r"/may be
/// a sub-class of <paramref name="subscribe rType"/>.</param>
/// <param name="subscribe rMethod">The method that should be
called
/// whenever the event is raised.</param>
/// <remarks>The caller should subscribe the <c>MyEventHandl er</c>
method to the event
/// <c>StaticEven t</clike this:
/// <code>
/// EventProviderTy pe.StaticEvent += new
SystemEventWeak Reference(this, "MyEventHandler ")).Delegat e;
/// </code>
/// Note that using this constructor does not allow the weak
reference wrapper to
/// unsubscribe from the event if its target is garbage collected,
and so the (admittedly tiny)
/// weak reference wrappers will build up in memory and event
delegate chains will get
/// longer and longer, cluttered with "dead" weak references.
Nonetheless, for small
/// applications where this may not matter, this constructor
offers a simpler calling sequence.
/// </remarks>
public SystemEventWeak Reference(objec t subscriber, Type
subscriberType, string subscriberMetho d) : this(subscriber ,
subscriberType, subscriberMetho d, null, null)
{ }

/// <summary>
/// The event handler that will really be subscribed to the event.
/// </summary>
/// <param name="sender">T he object that raised the event.</param>
/// <param name="e">Argume nts giving more information about the
event.</param>
public void Handler(object sender, System.EventArg s e)
{
object sub = this.Target;
if (sub != null)
{
this.Subscriber Method.Invoke(s ub, new object[] { sender, e });
}
else if (this.Provider != null)
{
this.Provider.R emoveEventHandl er(null, this.Delegate);
}
}

/// <summary>
/// The delegate to add to the event dispatch chain.
/// </summary>
/// <value>The event handler delegate for this object's
/// <see cref="Handler"/method.</value>
public System.EventHan dler Delegate
{
get { return new System.EventHan dler(this.Handl er); }
}
}

#endregion

Apr 26 '07 #7
Thanks for the sample code. I couldn't get it to work and could not
figure out why.

This is what I got from what you posted:
- You created an abstract class of "WeakEventRefer ence". This class
is used to create weak wrappers for specific events.
- The "SystemEventWea kReference" is a weak wrapper for a system event.

I tried creating a class that inherited "WeakEventRefer ence". I added
a Delegate property and Handler method, as you did with
"SystemEventWea kReference".

The problem I had is with the constructor. I tried passing the
MethodInfo property and "GetMethod(stri ng, BindingFlags)" does not
find the method in my class. I cannot see why !?!?!

Maybe an example of how you implemented this would be helpful.

Apr 30 '07 #8
On Apr 30, 8:24 am, MikeT <therien.m...@g mail.comwrote:
Thanks for the sample code. I couldn't get it to work and could not
figure out why.

This is what I got from what you posted:
- You created an abstract class of "WeakEventRefer ence". This class
is used to create weak wrappers for specific events.
- The "SystemEventWea kReference" is a weak wrapper for a system event.

I tried creating a class that inherited "WeakEventRefer ence". I added
a Delegate property and Handler method, as you did with
"SystemEventWea kReference".

The problem I had is with the constructor. I tried passing the
MethodInfo property and "GetMethod(stri ng, BindingFlags)" does not
find the method in my class. I cannot see why !?!?!

Maybe an example of how you implemented this would be helpful.
I'm at MIX'07 in Las Vegas until Wednesday. I've tagged this thread
and will get back and post a sample when I can.

Apr 30 '07 #9
On Apr 30, 8:24 am, MikeT <therien.m...@g mail.comwrote:
Thanks for the sample code. I couldn't get it to work and could not
figure out why.

This is what I got from what you posted:
- You created an abstract class of "WeakEventRefer ence". This class
is used to create weak wrappers for specific events.
- The "SystemEventWea kReference" is a weak wrapper for a system event.

I tried creating a class that inherited "WeakEventRefer ence". I added
a Delegate property and Handler method, as you did with
"SystemEventWea kReference".

The problem I had is with the constructor. I tried passing the
MethodInfo property and "GetMethod(stri ng, BindingFlags)" does not
find the method in my class. I cannot see why !?!?!

Maybe an example of how you implemented this would be helpful.
OK... here's a stitch of code where I subscribe to a static event via
a weak reference delegate:

Agama.ImageMana gement.GlobalIm ageCache.Defaul tMeasurementSys temChanged
+=
new SystemEventWeak Reference(this, typeof(frmSCGPr ofile),
"GlobalImageCac he_DefaultMeasu rementSystemCha nged",
typeof(Agama.Im ageManagement.G lobalImageCache ),
"DefaultMeasure mentSystemChang ed").Delegate ;

Be aware that this is subscribing to a _static_ event. Subscribing to
an instance event would be a bit different.

The object that's subscribing is an instance of frmSCGProfile, one of
my forms. The event handling method within frmSCGProfile is called
GlobalImageCach e_DefaultMeasur ementSystemChan ged. The event is
DefaultMeasurem entSystemChange d, exposed by the GlobalImageCach e
object.

Jon Skeet once pointed out to me that all of this could be improved,
or at least made typesafe, by using generics. That way, rather than
having a bunch of types that inherit from WeakReferenceEv entHandler,
you could just have one generic type.

May 1 '07 #10

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

Similar topics

8
3126
by: Dennis C. Drumm | last post by:
I have a class derived from a SortedList called SystemList that contains a list of objects indexed with a string value. The definition of the objects contained in the SortedList have a boolean field and an event that is fired if the boolean field value changes. The derived SortedList class has an override for the Add method. The Add method adds an event handler for the object's event for each new item added to the list. In the...
7
2443
by: cider123 | last post by:
I'm coding a project using the following article as reference: http://www.codeproject.com/csharp/DynamicPluginManager.asp In this type of project, plugins are loaded dynamically into a Plugin Manager. Your main application then hooks into the Plugin Manager. What I'm trying to figure out is how to impliment some form of raising
4
1117
by: Gonçalo Boléo | last post by:
I wan't to make a class that as a property that references a textbox and then cath the events of the text box in the class. In VB6 i make something like this: Dim WithEvents m_oTxt as VB.Textbox Property Let .... Property Set .... And then simply had events for the m_oTxt variable
6
2363
by: sylcheung | last post by:
Hi, How can I be notified when the document load is complet in JavaScript? I am referring to the whold document load is complete, mean all images/external files/frame/iframes have been loaded. I think there is a window.addEventListener() function but I am not sure which event to listen to. Thank you.
9
6060
by: Simon | last post by:
Hi, I have written an ActiveX object to resize images and upload them to a database, this all works fine but when I close internet explorer the process iexporer.exe is still running in my task manager and I can not launch anything from the desktop (eg. a web shortcut) without firt killing this process. The object is launched using JScript with the following code: var Launcher = new ActiveXObject("LaunchControl");
4
5295
by: Ty Salistean | last post by:
So, here is a wierd question that we have been discussing for a bit now. Does an event fire even though nothing is subscribed to listen to the event? For instance, does the Click event of a button fire even though nothing is subscribed to listen to the event. The answer is NO in a traditional Publisher/Subscriber design pattern (at least I think it is). I have stated that if nothing is subscribed, then the event never gets
22
16935
by: dvestal | last post by:
Suppose I have this: class C { public delegate void MyEventHandler(); public event MyEventHandler MyEvent; public void foo() { MyEvent(); // NullReferenceException? } }
44
8246
by: Smokey Grindle | last post by:
I have a list box on my form, but I need to databind it to a data table that is a private member of the form's class... so I basically have Public Class MyForm priate m_MyTable as new datatable End Class now where would I properly dispose of this? In the finalize method? I am loading the data for the table in a subroutine that is executed at form load, of course all the commands tied to it are wrapped in using blocks, but
5
4940
by: jehugaleahsa | last post by:
Hello: I am sure this question comes up a lot. I need to disable the controls on my Windows forms so that when the BindingSource is empty some the controls bound to it will be disabled. This will make it clear to the user that they have to create a new item first before they start working. This needs to be an easy process because there are many, many forms.
0
8895
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
8755
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,...
1
9191
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
9125
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8117
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
6710
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
6012
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
4523
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...
0
4787
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.