473,575 Members | 3,477 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Events - Delegates - Inheritance

Tim
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 returns true, I do not want to invoke the other
subscribers. The order in which the clients are notified is immaterial.

Problem:
How can the clients return a value? According to the MSDN documentation, the
return value is void in the delegate signature. I can change it to int, but
FxCop complains about it.
In Applied Microsoft .Net Framework, Jeffrey Richter talks about using
inheritance to solve this problem - "The derived type might decide not

to have the event forwarded on." Can someone please shed some light on how
to solve the problem?
Dec 14 '05 #1
4 5821
Hi,

I think the thing you talk about in the end applies to the case, when a
derived class decides not to call the parent's event handler (like in a
Click event in Windows forms), or something like that.

Multicast delegates always should return void (note the SHOULD in
there). This is because when you invoke them (or an event), and say you
have 10 event handlers registered, which return value would you use? For
this reason, multicast delegates should return void.

However, you should take a look at the GetInvocationLi st() method of the
MulticastDelega te class (which is what delegates are anyway). This
method will return an array of Delegate objects. You could then use this
array to invoke the delegates manually, and check for a return value, if
you want to continue. This would require only changes in the publisher,
the subscribers would subscribe to the events just as they do now. Of
course you should change the delegates to return a bool value.

When you have the Delegate[] array that is returned, you can go through
that one by one and call the DynamicInvoke() method on them, and check
the return value. Based on that, you can either continue invoking the
delegates or break the loop.

Hope this helps.

-Lenard
PS.
Here is a simple example (although I used static events and methods to
simplyfy):

class Program
{
static event CanContinueDele gate canContinue;

static void Main ( string[] args )
{
canContinue += new CanContinueDele gate ( canContinueEven t );
canContinue += new CanContinueDele gate ( canContinueEven t );
canContinue += new CanContinueDele gate ( canContinueEven t );

Delegate[] delegateList = canContinue.Get InvocationList ();
foreach ( Delegate d in delegateList )
{
if ( (bool)d.Dynamic Invoke ( new object[] { "not" } )
== false )
{
break;
}
}

}

static bool canContinueEven t ( string s )
{
Console.WriteLi ne ( s );
if ( s == "not" )
{
return false;
}
else
{
return true;
}
}
}

Tim wrote:
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 returns true, I do not want to invoke the other
subscribers. The order in which the clients are notified is immaterial.

Problem:
How can the clients return a value? According to the MSDN documentation, the
return value is void in the delegate signature. I can change it to int, but
FxCop complains about it.
In Applied Microsoft .Net Framework, Jeffrey Richter talks about using
inheritance to solve this problem - "The derived type might decide not

to have the event forwarded on." Can someone please shed some light on how
to solve the problem?

Dec 14 '05 #2
Or just keep it simple :)

using System;
using System.Collecti ons.Generic;
using System.Text;
using System.Collecti ons;

namespace Listeners
{
public interface IListener
{
bool Notify();
}
public class Client : IListener
{
private bool status = false;
private int ID = 0;
public Client(int ID)
{
this.ID = ID;
}
public void TurnOn()
{
this.status = true;
}
public bool Notify()
{
Console.WriteLi ne("Client "+ID.ToString() +" Notified");
return status;
}
}
class Broadcaster
{
private ArrayList listeners = new ArrayList();
// ASSERT listener is not null
public void Register(IListe ner listener) {
if (listener == null) { throw new ArgumentExcepti on(); }
listeners.Add(l istener);
}
public void Broadcast() {
foreach(IListen er l in listeners) {
if (l.Notify()) { break; }
}
}
static void Main(string[] args)
{
Client c1 = new Client(1);
Client c2 = new Client(2);
Client c3 = new Client(3);
c2.TurnOn();
Broadcaster b = new Broadcaster();
b.Register(c1);
b.Register(c2);
b.Register(c3);
b.Broadcast();
Console.ReadLin e();
}
}
}

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Dec 14 '05 #3
You can do this with events (in their original sense - no hacked return
value) quite easily, by using a different EventArgs class - ideally one
derived from CancelEventArgs , but any custom EventArgs derivative would do,
as long as it has a (settable) property on the class to allow you to
indicate failure.

Fully working example follows; outputs from the first 2 subscribers, but not
the last.

Hope this helps,

Marc

========

public class EventTest {
public static void Main() {
EventTest test = new EventTest();
test.MyEvent += DoSomething;
test.MyEvent += DoSomethingAndC omplain;
test.MyEvent += DoSomethingElse ;
test.FireTheEve nt();
}

static void DoSomething(obj ect sender,
System.Componen tModel.CancelEv entArgs e) {
Console.WriteLi ne("DoNothing") ;
}
static void DoSomethingAndC omplain(object sender,
System.Componen tModel.CancelEv entArgs e) {
Console.WriteLi ne("DoSomething AndComplain");
e.Cancel = true;
}
static void DoSomethingElse (object sender,
System.Componen tModel.CancelEv entArgs e) {
Console.WriteLi ne("DoSomething Else");
}

public void FireTheEvent() { // public accessor just to trigger
things
OnMyEvent();
}

public event System.Componen tModel.CancelEv entHandler MyEvent;

protected void OnMyEvent() {
if (MyEvent != null) {
System.Componen tModel.CancelEv entArgs args = new
System.Componen tModel.CancelEv entArgs();
foreach (System.Compone ntModel.CancelE ventHandler listener
in MyEvent.GetInvo cationList()) {
listener(this, args);
if (args.Cancel)
break;
}
}
}

}

"Tim" <Ti*@discussion s.microsoft.com > wrote in message
news:71******** *************** ***********@mic rosoft.com...
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 returns true, I do not want to invoke the other
subscribers. The order in which the clients are notified is immaterial.

Problem:
How can the clients return a value? According to the MSDN documentation,
the
return value is void in the delegate signature. I can change it to int,
but
FxCop complains about it.
In Applied Microsoft .Net Framework, Jeffrey Richter talks about using
inheritance to solve this problem - "The derived type might decide not

to have the event forwarded on." Can someone please shed some light on how
to solve the problem?

Dec 14 '05 #4
Tim
Thanks Marc. That's exactly what I was looking for.

"Marc Gravell" wrote:
You can do this with events (in their original sense - no hacked return
value) quite easily, by using a different EventArgs class - ideally one
derived from CancelEventArgs , but any custom EventArgs derivative would do,
as long as it has a (settable) property on the class to allow you to
indicate failure.

Fully working example follows; outputs from the first 2 subscribers, but not
the last.

Hope this helps,

Marc

========

public class EventTest {
public static void Main() {
EventTest test = new EventTest();
test.MyEvent += DoSomething;
test.MyEvent += DoSomethingAndC omplain;
test.MyEvent += DoSomethingElse ;
test.FireTheEve nt();
}

static void DoSomething(obj ect sender,
System.Componen tModel.CancelEv entArgs e) {
Console.WriteLi ne("DoNothing") ;
}
static void DoSomethingAndC omplain(object sender,
System.Componen tModel.CancelEv entArgs e) {
Console.WriteLi ne("DoSomething AndComplain");
e.Cancel = true;
}
static void DoSomethingElse (object sender,
System.Componen tModel.CancelEv entArgs e) {
Console.WriteLi ne("DoSomething Else");
}

public void FireTheEvent() { // public accessor just to trigger
things
OnMyEvent();
}

public event System.Componen tModel.CancelEv entHandler MyEvent;

protected void OnMyEvent() {
if (MyEvent != null) {
System.Componen tModel.CancelEv entArgs args = new
System.Componen tModel.CancelEv entArgs();
foreach (System.Compone ntModel.CancelE ventHandler listener
in MyEvent.GetInvo cationList()) {
listener(this, args);
if (args.Cancel)
break;
}
}
}

}

"Tim" <Ti*@discussion s.microsoft.com > wrote in message
news:71******** *************** ***********@mic rosoft.com...
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 returns true, I do not want to invoke the other
subscribers. The order in which the clients are notified is immaterial.

Problem:
How can the clients return a value? According to the MSDN documentation,
the
return value is void in the delegate signature. I can change it to int,
but
FxCop complains about it.
In Applied Microsoft .Net Framework, Jeffrey Richter talks about using
inheritance to solve this problem - "The derived type might decide not

to have the event forwarded on." Can someone please shed some light on how
to solve the problem?


Dec 14 '05 #5

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

Similar topics

4
1764
by: Marty McDonald | last post by:
It is still unclear to me why we would use events when delegates seem to do just fine. People say that events make it so the publisher doesn't need to know about the listeners. What does that mean? Why are events better than delegates? Thanks
2
2093
by: Eric Newton | last post by:
VB's more declarative nature of handling events is golden. I'm hoping C# will acquire this type of deal, in addition to the anonymous delegates. could do same as vb (actually would be easier to parse then vb due to braces) whereas you look for Handles keyword after method sig, but before opening brace of the method. compiler would...
4
22867
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....
11
1853
by: Nicky Smith | last post by:
Hello, I'm studying a book on VB.net Win apps, and I'm reading a section on events and delegates and raising events. Is it just me, or is this not just subs dressed up as something else? I mean, for one, delegates point to subs, so when you call a delegate, why not just call the sub dierectly and not bother adding the extra code...
8
1760
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...
30
3625
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...
2
2335
by: kristian.freed | last post by:
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...
5
2389
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...
7
3410
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...
0
7845
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...
0
8281
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...
0
8143
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...
0
6515
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...
1
5664
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...
0
3778
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...
0
3797
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2286
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
1107
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...

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.