473,789 Members | 2,679 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Order of firing delegates


I'm working through some code that uses events and delegates.

Pardon me, but I understand delegates to be a little like function
callbacks in c.

I coded up a code sample and started playing with it -- but what I don't
understand is this.

Shouldn't an event behave asynchronously?

Like if I fire an event, and it's handler takes 5 seconds to occur, and
then I fire a second event and it's handler takes 2 seconds to occur,
shouldn't the 2nd handler's results show up first?

When I run my code in Studio, it seems like it waits for the first
handler to finish, and then goes to the second handler. That seems
more like something I would expect from VB5 -- not c# .NET!

using System;
using System.Diagnost ics;
using System.Threadin g;

namespace DelegateTest
{
/// <summary>
/// Summary description for Class1.
/// </summary>
///
//create delegate object
public delegate void MyHandler1(obje ct sender, MyEventArgs e);
public delegate void MyHandler2(obje ct sender, MyEventArgs e);
//create event handler methods
class A
{
public const string m_id="Class A";

public void OnHandler1(obje ct sender, MyEventArgs e)
{

//this should delay 1 for a while
while(true) Thread.Sleep(10 00);

Debug.WriteLine ("I am in OnHandler1 "
+ "and MyEventArgs is {0}", e.m_id);
}

public void OnHandler2(obje ct sender, MyEventArgs e)
{

//this should fire first.
Debug.WriteLine ("I am in OnHandler2 " +
"and MyEventArgs is {0}", e.m_id);
}
public A(B b)
{
MyHandler1 d1= new MyHandler1(OnHa ndler1);
MyHandler2 d2= new MyHandler2(OnHa ndler2);
b.Event1 += d1;
b.Event2 += d2;
}

}

class B
{
public event MyHandler1 Event1;
public event MyHandler2 Event2;

public void FireEvent1(MyEv entArgs e)
{
if(Event1 != null)
{

Event1(this, e);
}
}

public void FireEvent2(MyEv entArgs e)
{
if(Event2 != null)
{

Event2(this, e);
}
}
}

public class MyEventArgs {
public string m_id;
}

class Delegator
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//

B b = new B();
A a = new A(b);

MyEventArgs e1 = new MyEventArgs();
MyEventArgs e2 = new MyEventArgs();

e1.m_id="Event args for event 1";
e2.m_id="Event args for event 2";

b.FireEvent1(e1 );
b.FireEvent2(e2 );
}
}
}

Nov 17 '05 #1
2 1366
>Shouldn't an event behave asynchronously?
No, event hanlers get invoked synchronously. Every delegate in C# is
multicast, it consists of a chain of elements which you can obtain by
using MulticastDelege te.GetInvocatio nList method. If you want to invoke
them asynchronously, call GetInvocationLi st first, then invoke each
delegate in the returned array in a separate thread.

-----
Thi - http://thith.blogspot.com

Nov 17 '05 #2
> Shouldn't an event behave asynchronously?

No. Multicast delegates are nothing more than a language shorthand for
calling a list of methods in sequence. It is the .NET version of the
Observable / Observer pattern, which, if you look to Java, works
synchronously as well.

You can introduce asynchrony as Truong pounts out, but you don't get it
if you don't ask for it.

In fact, this makes things much easier to understand, particularly when
you start driving the UI using events. Asynchrony adds complexity (just
look at the number of posts in this newsgroup about threading
problems), and in many cases it's unnecessary for the smooth running of
an application. Making every event delegate run in its own thread would
introduce a lot of additional complexity and overhead that would bring
much benefit.

It's easy to introduce multithreading in C# where you decide that it
makes a difference. Otherwise, what you get is synchronous behaviour.

Nov 17 '05 #3

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

Similar topics

2
1592
by: John A. Bailo | last post by:
I'm working through some code that uses events and delegates. Pardon me, but I understand delegates to be a little like function callbacks in c. I coded up a code sample and started playing with it -- but what I don't understand is this. Shouldn't an event behave asynchronously?
1
6271
by: A. Elamiri | last post by:
Hello, For some reason the FileSystemWatcher events aren't firing. The code that sets the event delegates .... asmwatch.Path = AppDomain.CurrentDomain.BaseDirectory + "services\\"; asmwatch.Created +=new FileSystemEventHandler(asmwatch_Created);
5
16051
by: Jason | last post by:
I have an application that uses a timer. I've created a function called TickEvent that I "assigned" to the timer1.Tick event: this.timer1.Interval = 1000; this.timer1.Tick += new System.EventHandler(this.TickEvent); .... private void TickEvent(object sender, System.EventArgs e) { liSecondsElapsed++; DateTime lsTime = Convert.ToDateTime(liSecondsElapsed);
5
10807
by: Richard | last post by:
All, I have a worker thread that fires events across threads to both GUI objects and thread agnostic objects. My code is working but I want to be assured that it did it "the right way"... Question: Is there a better way? According to the .NET docs that I read all that I have to do to fire my custom "OnSynchronizationStatusChange()" event is: protected void OnSynchronizationStatusChange(SynchronizationEventArgs e)
3
2304
by: Mike | last post by:
Hi, I am adding controls dynamically in a WebForm, but none of these controls' events fire. Here is the class code I am using. I have tried so many things, but nothing works :-( namespace WebApplication1 { using System;
8
1073
by: Bernie Yaeger | last post by:
I know I'm not getting this clearly: I set up a delegate to execute a method. I've done this with no problem re validating methods. For example: I set up the delegate like this: Delegate Sub callm_dropdown(ByVal sender As Object, ByVal e As System.EventArgs) Dim delegd As callm_dropdown Then I call it, say in a click event of a button:
8
2638
by: Frank van Vugt | last post by:
Hi, If during a transaction a number of deferred triggers are fired, what will be their execution order upon the commit? Will they be executed in order of firing or alfabetically or something entirely different? The docs only mention regular triggers being executed alfabetically.
6
1743
by: utkarsh | last post by:
Hi All, I am using the following method "FireAsync" (i got the following information from the google groups) to fire the event for all the subscribers. Is there another way to fire the event to all the subscriber asynchronously efficiently. As because in my application this method is being call 60-100 times a second.
2
2670
by: mswlogo | last post by:
I looked high and low for code to do this and finally found some VB code that did it right. This is a C# flavor of it. public event EventHandler<EventArgsMyEventToBeFired; public void FireEvent(Guid instanceId, string handler) { EventArgs e = new EventArgs(instanceId);
4
2045
by: Joergen Bech | last post by:
I sometimes use delegates for broadcasting "StateChanged" events, i.e. if I have multiple forms and/or controls that need updating at the same time as the result of a change in a global/common object, I keep local references to this object in each UI object, e.g. Private WithEvents _tools As RepeatTools and catch messages in an event handler like this:
0
9666
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
9511
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
10408
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
10139
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
9983
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...
1
7529
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
5551
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3700
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2909
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.