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);
}
}
}