473,395 Members | 1,666 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

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.Diagnostics;
using System.Threading;

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

public void OnHandler1(object sender, MyEventArgs e)
{

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

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

public void OnHandler2(object 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(OnHandler1);
MyHandler2 d2= new MyHandler2(OnHandler2);
b.Event1 += d1;
b.Event2 += d2;
}

}

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

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

Event1(this, e);
}
}

public void FireEvent2(MyEventArgs 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 9 '05 #1
2 1568
>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 MulticastDelegete.GetInvocationList method. If you want to invoke
them asynchronously, call GetInvocationList first, then invoke each
delegate in the returned array in a separate thread.

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

Nov 9 '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 9 '05 #3

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

Similar topics

1
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\\"; ...
5
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...
5
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"... ...
2
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...
3
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...
8
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...
6
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...
2
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...
4
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...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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,...
0
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...
0
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...
0
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...
0
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...

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.