473,729 Members | 2,185 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Advanced use of delegates to automatically disconnect delegates from a set of events

Hi,

I currently work in a project written fully in C# where we make
extensive use of delegates and events. We have a model where a "state",
an object holding data but not much code but which fires events when
the data changes, is often the central part. Connected to these states
are various observers that act on changes in data, by altering the
information presented to the user, executing code and so on, each
observer with its own function.

A situation that occurs very frequently because of this design is the
need to connect or disconnect an observer to/from a state. The connect
method will usually just hook a number of events, and the disconnect
method should unhook each of these events so the observer can be used
again on another state or be garbage collected. A repetitive and error
prone task is thus to make sure that these two methods are in sync. To
help with this, I would like to create a class with the responsibility
of keeping track of all events that have been connected, and when
requested disconnect them all. The interface would look something like
this:

interface IDelegateConnec tor
{
void ConnectDelegate <T>(T evt, T del) where T : Delegate;
void DisconnectAll() ;
}

Where you would connect delegate del to event evt. You can however not
use Delegate as base class constraint to generic methods, so instead it
would have to be something like this:

interface IDelegateConnec tor
{
void ConnectDelegate (DelegateType1 evt, DelegateType1 del);
void ConnectDelegate (DelegateType2 evt, DelegateType2 del);
void ConnectDelegate (DelegateType3 evt, DelegateType3 del);

void DisconnectAll() ;
}

where I manually create one overload for each delegate/event type that
I am interested in connecting this way. There are a number of problems
with these interfaces and their implementation, but this should be
enough to present the idea of what I want.

Does anyone know how this would be possible to implement or know of
another method to simplify my event handling code?

/ Kristian

Nov 16 '06 #1
2 2344
Have you had a look into multicast delegates?
MulticastDelega te Members :
CombineImpl :Overridden. Combines this Delegate with the specified
Delegate to form a new delegate.
RemoveImpl :Overridden. Removes an element from the invocation list of
this MulticastDelega te that is equal to the specified delegate.
....
....
"
MulticastDelega te is a special class. Compilers and other tools can
derive from this class, but you cannot derive from it explicitly. The
same is true of the Delegate class.

A MulticastDelega te has a linked list of delegates, called an
invocation list, consisting of one or more elements. When a multicast
delegate is invoked, the delegates in the invocation list are called
synchronously in the order in which they appear. If an error occurs
during execution of the list then an exception is thrown.

"
http://msdn2.microsoft.com/en-gb/lib...e_members.aspx

Maby i'm not understanding your question compleately.

Have a great day!

Austin

On Nov 16, 2:18 am, kristian.fr...@ gmail.com wrote:
Hi,

I currently work in a project written fully in C# where we make
extensive use of delegates and events. We have a model where a "state",
an object holding data but not much code but which fires events when
the data changes, is often the central part. Connected to these states
are various observers that act on changes in data, by altering the
information presented to the user, executing code and so on, each
observer with its own function.

A situation that occurs very frequently because of this design is the
need to connect or disconnect an observer to/from a state. The connect
method will usually just hook a number of events, and the disconnect
method should unhook each of these events so the observer can be used
again on another state or be garbage collected. A repetitive and error
prone task is thus to make sure that these two methods are in sync. To
help with this, I would like to create a class with the responsibility
of keeping track of all events that have been connected, and when
requested disconnect them all. The interface would look something like
this:

interface IDelegateConnec tor
{
void ConnectDelegate <T>(T evt, T del) where T : Delegate;
void DisconnectAll() ;
}

Where you would connect delegate del to event evt. You can however not
use Delegate as base class constraint to generic methods, so instead it
would have to be something like this:

interface IDelegateConnec tor
{
void ConnectDelegate (DelegateType1 evt, DelegateType1 del);
void ConnectDelegate (DelegateType2 evt, DelegateType2 del);
void ConnectDelegate (DelegateType3 evt, DelegateType3 del);

void DisconnectAll() ;
}

where I manually create one overload for each delegate/event type that
I am interested in connecting this way. There are a number of problems
with these interfaces and their implementation, but this should be
enough to present the idea of what I want.

Does anyone know how this would be possible to implement or know of
another method to simplify my event handling code?

/ Kristian
Nov 16 '06 #2
Well your question made me curious so I coded this as an experiment:

public abstract class MCV
{
public delegate void ClearHandler(ob ject source, EventArgs
e);
public delegate void RefreshHandler( object source, EventArgs
e);
public delegate void EnableHandler(o bject source, EventArgs
e);
public delegate void DisableHandler( object source,
DisableEventArg s e);
public class DisableEventArg s : EventArgs
{
public readonly string Message = "";
public DisableEventArg s(string message)
{
this.Message = message;
}
}
public interface IViewable
{
bool Clear();
bool Refresh();
bool Enable();
bool Disable(string message);
}
public interface IViewableEvents
{
MCV.DisableHand ler GetDisableHandl er();
MCV.EnableHandl er GetEnableHandle r();
MCV.ClearHandle r GetClearHandler ();
MCV.RefreshHand ler GetRefreshHandl er();
}
} // end MCV class

The controller class fires events to all registered Views using
IViewableEvents , but each View can be individually disabled using
IViewable. A disabled View will ignore notify and refresh events.

http://www.geocities.com/jeff_louie/oop32.htm

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Nov 18 '06 #3

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

Similar topics

0
1366
by: BlueMonkMN | last post by:
I've been trying to think of the right way to design relationships between objects with different desired lifetimes that raise events. If an event source is a relatively permanent object and the event sink is on an object that can come and go, what is the proper way to deal with adding and removing the handler to the event list? Should the event sink make sure to remove itself from the source's event list before all other references to it...
4
22885
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
15
6626
by: Iced Crow | last post by:
In C# I know that you can use delegates to assing multiple addresses of sub and functions to a delegate and have it fire multiple procedures... How do I do this in VB? I only know of assigning a single method to a delegate in VB.NET. I want to use it as in C#... to fire multiple events. Thanks in advance!
8
1776
by: Nicky Smith | last post by:
Hello, I'm reading Mike Gunderloy's Mcad Vb.net book, and I've also read the MS press Mcad book for the same topic ".. Windows based applications with VB.net" for exam 70-306. In the sections in both books that try to teach the use of delagates and events, I'm really lost, and to make matters worse, I've written a user-control that fires events for the host form, and this works without delegates!
1
2113
by: lallous | last post by:
Hello I am not very experienced with this issue and would your opinion on whether it is healthy or not: 1) I created an ATL COM object (say MyCOM): - that supports connection points - that exposes couple of methods such as: BeginOperation()
0
13091
ADezii
by: ADezii | last post by:
Not all ADO Power Users realize that there are Events, specifically related to the Connection and Recordset Objects, for which they can write code for. If one is aware of these Events, it is not exactly intuitive as to how you would access them. Below, please find a listing of Events which are exposed by the ADO Recordset and Connection Objects. I will also demonstrate the mechanism by which you, the ADO programmer, can make use of these...
7
3419
by: Siegfried Heintze | last post by:
I'm studying the book "Microsoft Visual Basic.NET Language Reference" and I would like some clarify the difference between events and delegates. On page 156 I see a WinForms example of timer that uses the "WithEvents" and events. There is another example on page 124 that shows how to use delegates to sort an array. I don't understand the difference between events and delegates. Are they redundant features? How do I decide which to use? ...
9
1890
by: Scott Gifford | last post by:
I have a question about concurrency and delegates. Say I have a class roughly like this: public class Class1 { public delegate void MyEventHandler(); private event MyEventHandler onMyEvent; public event OnMyEvent
69
5583
by: raylopez99 | last post by:
They usually don't teach you in most textbooks I've seen that delegates can be used to call class methods from classes that are 'unaware' of the delegate, so long as the class has the same signature for the method (i.e., as below, int Square (int)). Here is an example to show that feature. Note class "UnAwareClass" has its methods Square and Cuber called by a class DelegateClass. This is because these methods in UnAwareClass have the...
0
8925
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
8763
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
9428
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...
0
9288
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...
0
9154
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
8156
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
6026
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();...
2
2692
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2166
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.