473,805 Members | 2,055 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Clearing Events without -=

Hi,

I have a situation where I need to clear the event sinks from an event
inside a custom class. But I don't know which methods signed up for that
event.

Consider the following example:

public class B
{
public event System.EventHan dler DoneIt;

// ....
}

B b = new B();
b.DoneIt += X;

Now eventually suppose I want to "reset" b so that DoneIt == null but I
don't want to completely generate a new object, just the event sinks.
Typically this is done using

b.DoneIt -= X;

But in this case we don't know what X is. B is in a class library and we
have no control or knowedge of what the consumers of that class might do
with DoneIt.

My question is: Is there a way to have b force DoneIt to be null without
explicitly knowing the right hand side of += since it happened outside our
code?

Thanks in advance,
Michael

ps In case you haven't tried this before: b.DoneIt = null; does not compile.
Nov 15 '05 #1
13 13921
Michael Kennedy [UB] <mk******@REMOV ETHIS.unitedbin ary.com> wrote:
I have a situation where I need to clear the event sinks from an event
inside a custom class. But I don't know which methods signed up for that
event.


If you are not the "owner" of the custom class, you can't do this.
Within the custom class you can clear the event, but if the custom
class doesn't make any means of clearing the event available to you, it
presumably doesn't want you to be able to do so.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #2
Using reflection, you can do b.GetType().Get Events() or
b.GetType().Get Event() to find the particular event of interest and use the
EventInfo.Remov eEventHandler() to remove it.

I haven't done this, but a quick look at the docs would lead me to start
here.

Pete

"Michael Kennedy [UB]" <mk******@REMOV ETHIS.unitedbin ary.com> wrote in
message news:uv******** ******@tk2msftn gp13.phx.gbl...
Hi,

I have a situation where I need to clear the event sinks from an event
inside a custom class. But I don't know which methods signed up for that
event.

Consider the following example:

public class B
{
public event System.EventHan dler DoneIt;

// ....
}

B b = new B();
b.DoneIt += X;

Now eventually suppose I want to "reset" b so that DoneIt == null but I
don't want to completely generate a new object, just the event sinks.
Typically this is done using

b.DoneIt -= X;

But in this case we don't know what X is. B is in a class library and we
have no control or knowedge of what the consumers of that class might do
with DoneIt.

My question is: Is there a way to have b force DoneIt to be null without
explicitly knowing the right hand side of += since it happened outside our
code?

Thanks in advance,
Michael

ps In case you haven't tried this before: b.DoneIt = null; does not compile.

Nov 15 '05 #3
"Michael Kennedy [UB]" <mk******@REMOV ETHIS.unitedbin ary.com> wrote:

<snip>
ps In case you haven't tried this before: b.DoneIt = null; does not compile.


Thats because you used

public event System.EventHan dler DoneIt;

"event" protects it from that sort of "abuse". If you change it to

public System.EventHan dler DoneIt;

the compilation error will go away - however now you have a publically
accessible field that clients of the object can abuse without the knowledge
of the object - a situation that should be avoided. Simply create a public method
in class B to clear the event sink list, e.g.:

public void ClearDoneIt(){
// Place any Checks here to determine
// it you want to follow the "suggestion "
// to clear DoneIt
DoneIt = null;
} // End method B.RaiseDoneIt

that way you won't have to leave the event sink list so exposed.

Source Code follows:

#define ClearEvent
using System;

namespace ClearEvent {

class TestDriver {
static void Main(string[] args) {

B b = new B();
DoneItSubscribe r s1 = new DoneItSubscribe r( "First", b );
DoneItSubscribe r s2 = new DoneItSubscribe r( "Second", b );
Console.WriteLi ne( "Raising DoneIt Event." );
b.RaiseDoneIt() ;
Console.WriteLi ne( "Clearing DoneIt Event sinks." );
#if ClearEvent
b.ClearDoneIt() ;
#else
b.DoneIt = null;
#endif
Console.WriteLi ne( "Raising DoneIt Event again." );
b.RaiseDoneIt() ;
}
}

public class B {

#if ClearEvent
public event System.EventHan dler DoneIt;
#else
public System.EventHan dler DoneIt;
#endif

public void RaiseDoneIt(){
OnDoneIt( EventArgs.Empty );
} // End method B.RaiseDoneIt

public void ClearDoneIt(){
// Place any Checks here to determine
// it you want to follow the "suggestion "
// to clear DoneIt
DoneIt = null;
} // End method B.RaiseDoneIt

// "Publishing Events Defensively" p.108
// "Programmin g .NET Components" by Juval Löwry, April 2003 O'Reilly & Associates Inc
// ISBN 0596003471
protected void OnDoneIt( EventArgs e ){
if (null == DoneIt ) return;

Delegate[] delegates = DoneIt.GetInvoc ationList();
foreach( Delegate del in delegates ){
EventHandler sink = (EventHandler)d el;
try {
sink( this, e );

} catch {
Console.WriteLi ne( "OnDoneIt: Eventhandler raised exception." );
}
}
} // End method B.OnDoneIt

} // end class B

public class DoneItSubscribe r {
private string name_;

public DoneItSubscribe r( string name, B eventSource ) {
name_ = name;
eventSource.Don eIt += new EventHandler( HandleDoneIt );
}

public void HandleDoneIt( object sender, EventArgs e ){
Console.WriteLi ne(
name_ + ": handled DoneIt."
);
}
} // end class DoneItSubscribe r

}

Nov 15 '05 #4
Hi Pete,

That's an interesting idea. Although working with the typeof(B) alone it
seems like it is not possible to effect instance level events. Maybe it
could effect something with the static events, but I will definitely have a
look.

Thanks!
Michael

"Pete Davis" <pd******@hotma il.com> wrote in message
news:25******** *************** *******@news.me ganetnews.com.. .
Using reflection, you can do b.GetType().Get Events() or
b.GetType().Get Event() to find the particular event of interest and use the EventInfo.Remov eEventHandler() to remove it.

I haven't done this, but a quick look at the docs would lead me to start
here.

Pete

"Michael Kennedy [UB]" <mk******@REMOV ETHIS.unitedbin ary.com> wrote in
message news:uv******** ******@tk2msftn gp13.phx.gbl...
Hi,

I have a situation where I need to clear the event sinks from an event
inside a custom class. But I don't know which methods signed up for that
event.

Consider the following example:

public class B
{
public event System.EventHan dler DoneIt;

// ....
}

B b = new B();
b.DoneIt += X;

Now eventually suppose I want to "reset" b so that DoneIt == null but I
don't want to completely generate a new object, just the event sinks.
Typically this is done using

b.DoneIt -= X;

But in this case we don't know what X is. B is in a class library and we
have no control or knowedge of what the consumers of that class might do
with DoneIt.

My question is: Is there a way to have b force DoneIt to be null without
explicitly knowing the right hand side of += since it happened outside our code?

Thanks in advance,
Michael

ps In case you haven't tried this before: b.DoneIt = null; does not

compile.


Nov 15 '05 #5
Hi,

That is a good idea. I'll see how this idea fits into my architecture. It
looks like it could be a winner.

Thanks!
Michael
"UAError" <nu**@null.null > wrote in message
news:p1******** *************** *********@4ax.c om...
"Michael Kennedy [UB]" <mk******@REMOV ETHIS.unitedbin ary.com> wrote:

<snip>
ps In case you haven't tried this before: b.DoneIt = null; does not
compile.
Thats because you used

public event System.EventHan dler DoneIt;

"event" protects it from that sort of "abuse". If you change it to

public System.EventHan dler DoneIt;

the compilation error will go away - however now you have a publically
accessible field that clients of the object can abuse without the knowledge of the object - a situation that should be avoided. Simply create a public method in class B to clear the event sink list, e.g.:

public void ClearDoneIt(){
// Place any Checks here to determine
// it you want to follow the "suggestion "
// to clear DoneIt
DoneIt = null;
} // End method B.RaiseDoneIt

that way you won't have to leave the event sink list so exposed.

Source Code follows:

#define ClearEvent
using System;

namespace ClearEvent {

class TestDriver {
static void Main(string[] args) {

B b = new B();
DoneItSubscribe r s1 = new DoneItSubscribe r( "First", b );
DoneItSubscribe r s2 = new DoneItSubscribe r( "Second", b );
Console.WriteLi ne( "Raising DoneIt Event." );
b.RaiseDoneIt() ;
Console.WriteLi ne( "Clearing DoneIt Event sinks." );
#if ClearEvent
b.ClearDoneIt() ;
#else
b.DoneIt = null;
#endif
Console.WriteLi ne( "Raising DoneIt Event again." );
b.RaiseDoneIt() ;
}
}

public class B {

#if ClearEvent
public event System.EventHan dler DoneIt;
#else
public System.EventHan dler DoneIt;
#endif

public void RaiseDoneIt(){
OnDoneIt( EventArgs.Empty );
} // End method B.RaiseDoneIt

public void ClearDoneIt(){
// Place any Checks here to determine
// it you want to follow the "suggestion "
// to clear DoneIt
DoneIt = null;
} // End method B.RaiseDoneIt

// "Publishing Events Defensively" p.108
// "Programmin g .NET Components" by Juval Löwry, April 2003 O'Reilly & Associates Inc // ISBN 0596003471
protected void OnDoneIt( EventArgs e ){
if (null == DoneIt ) return;

Delegate[] delegates = DoneIt.GetInvoc ationList();
foreach( Delegate del in delegates ){
EventHandler sink = (EventHandler)d el;
try {
sink( this, e );

} catch {
Console.WriteLi ne( "OnDoneIt: Eventhandler raised exception." ); }
}
} // End method B.OnDoneIt

} // end class B

public class DoneItSubscribe r {
private string name_;

public DoneItSubscribe r( string name, B eventSource ) {
name_ = name;
eventSource.Don eIt += new EventHandler( HandleDoneIt );
}

public void HandleDoneIt( object sender, EventArgs e ){
Console.WriteLi ne(
name_ + ": handled DoneIt."
);
}
} // end class DoneItSubscribe r

}

Nov 15 '05 #6
Hi Jon,

In the situation I outlined, I was the owner of the custom class. But I can
see how if you had a public event and it was "nullable" as I was asking for,
then other classes could mess-up the events by nulling them since it is
public and would be accessable in that way to everyone.

Thanks!
Michael

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Michael Kennedy [UB] <mk******@REMOV ETHIS.unitedbin ary.com> wrote:
I have a situation where I need to clear the event sinks from an event
inside a custom class. But I don't know which methods signed up for that
event.


If you are not the "owner" of the custom class, you can't do this.
Within the custom class you can clear the event, but if the custom
class doesn't make any means of clearing the event available to you, it
presumably doesn't want you to be able to do so.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #7
Hi Michael,

Thanks for posting. I think the EventInfo.Remov eEventHandler() method can
affect instance level events:

http://msdn.microsoft.com/library/de...us/cpref/html/
frlrfsystemrefl ectioneventinfo classremoveeven thandlertopic.a sp

As we can see, the first parameter of the method is "object target". It is
the instance that the method operates on to remove the delegate from.

On the other hand, the EventInfo.Remov eEventHandler() method cannot achieve
your goal. The reason is similar to the "-=" operator. For the method to
operate, it needs a second parameter to identify the delegate to remove. If
we have no reference to the delegate, we cannot remove it.

I hope this makes sense.

Regards,

Felix Wang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #8
Hi Jon,

I think that we can achieve the goal with Reflection, even if we are not
the "owner" of the custom class. The following is a simple C# Console
Application for demonstraton:

using System;
using System.Reflecti on;

public delegate void MyDelegate();

public class B
{
public event MyDelegate AEvent;
public void RaiseAEvent()
{
if (AEvent != null)
{
AEvent();
} else Console.WriteLi ne("Event delegate is null");
}
}

public class ClassForMain
{
public static void Main(string[] args)
{
B b = new B();
b.AEvent += new MyDelegate(Hell o);
b.RaiseAEvent() ;

Type t = typeof(B);
FieldInfo f = t.GetField("AEv ent", BindingFlags.In stance |
BindingFlags.No nPublic);
f.SetValue(b,nu ll);
b.RaiseAEvent() ;
}

public static void Hello()
{
Console.WriteLi ne("Hello");
}
}

Regards,

Felix Wang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #9
Felix Wang <v-*****@online.mi crosoft.com> wrote:
I think that we can achieve the goal with Reflection, even if we are not
the "owner" of the custom class. The following is a simple C# Console
Application for demonstraton:


<snip>

Your code is assuming that:

a) You have sufficient access to modify private fields in the relevant
class
b) The event is defined in such a way that there's a field of the same
name

Neither need be true.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #10

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

Similar topics

0
5034
by: Charles Blaquière | last post by:
While noodling around, looking for a good layout for an "events calendar" page, I came upon a problem that has me stymied. Have a look at http://kpuc.org/events/upcoming-2.html . The basic structure of each event is: Event div Left-floated image Event header div
18
8092
by: Niels | last post by:
Hi group, I have some problems with clearing floated divs. My usual method works fine in Konqueror, but not in Firefox. Here's an example: <html><body> <div id='left' style='float:left; border:1px solid red;'>Floated left</div> <div id='right' style='float:right; border:1px solid blue;'>Floated right</div>
2
2301
by: Andrey Tarasevich | last post by:
Hello Consider the following HTML code sketch <div> <img src="..." style="float: left"> <p>Paragraph text</p> </div> <hr>
14
12157
by: JPRoot | last post by:
Hi I use the following syntax to have events inherited from base to child classes which works nicely (virtual and override keyword on events). But I am wondering if it is a "supported" way of using events since I never saw it used anywhere in MSDN documentation/samples?! Or it will just break when I upgrade to .NET Framework 2.x in the coming years namespace MyNamespac public delegate void MyDel() public class MyBase public virtual...
3
15059
by: Brad | last post by:
I'm working with a DataGrid in C#, and the user needs to be able add and remove columns from the DataGrid on the fly, without opening and closing the form. The scenario is this. I have a setup table that allows users to rename columns, resize columns, and select whether or not they want them to be visible or not. While the user is working with a certain set of data, they will want to see certain columns, and in certain situations they...
0
1032
by: Lappis | last post by:
I created a handler for evenlog EntryWritten, which works fine until someone clears the log. After clearing the log it won't receice events any longer. Is this a bug or feature? If a feature how to circumvent it? \\Lappis
2
1320
by: Verdagon | last post by:
Hey everyone. I have this function in my form called "Display", which I call every time the load, resize, and paint events are called. It works fine on paint and resize, but on load it doesnt happen. When the form loads, it draws what I want, but then after a few milliseconds it disappears. It's being drawn over by something else. What's drawing over it? I've tried using SetStyle, and setting UserPaint and AllPaintingInWmPaint, and...
30
3662
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
1
1747
by: ray well | last post by:
i'm loading a combobox from a database in code, by setting the the DataSouce to a table, and the DisplayMember to a field. it loads the first row into the text area of the combobox automatically. i don't want that. i used to clear it up by setting ComboBox1.Text="", after loading it. but i had to put the combobox on a tab page of a tab control. ComboBox1.Text="" works only if the tab page has the focus when that code
0
9716
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
10360
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
10366
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
10105
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
9185
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...
0
5542
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
5677
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4323
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
3
3007
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.