C#•Use Asynchronous Delegates

Listing 4. .NET has streamlined asynchronous programming, thanks to the introduction of asynchronous delegates such as the BeginInvoke method. But watch out—you can't be sure of the order in which the target of the invocation method receives calls. Usually the receive order reflects the invocation order, so a few tests might lead you to incorrect conclusions.

delegate void X(string sender, string param);

private void button1_Click(object sender, 
	System.EventArgs e) {
MyClass c1 = new MyClass ();
X mydel1 = new X(c1.MethodA);

MyClass c2 = new MyClass ();
X mydel2 = new X(c2.MethodA );

for (int i =0; i<=100;i++) {
	mydel1.BeginInvoke("A", i.ToString 
		(),null,null);
	mydel1.BeginInvoke("B", i.ToString 
		(),null,null);
} 
// EndInvoke call is omitted for brevity, but you 
// should always call it to avoid memory leaks
}
	 
public class MyClass {
	
public void MethodA(string sender, string param ) {
	Debug.WriteLine ("Method A received call 
		from " + sender + " with param " + 
		param);	 
	//do some work
	System.Threading.Thread.Sleep (1000);
}
}