473,778 Members | 2,804 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 9 '05 #1
2 1591
>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 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
6268
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
16049
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
10803
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)
2
1366
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?
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:
6
1742
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
2668
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
2044
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
9629
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
9465
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,...
1
10068
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
9923
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
8954
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...
1
7474
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
6723
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();...
0
5370
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...
1
4031
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

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.