Thursday, April 12, 2007

Calling Delegates Asynchronously

using System;
using System.Threading;

public class Test
{
delegate int TestDelegate(string parameter);
static void Main()
{
TestDelegate d = new TestDelegate(PrintOut);
d.BeginInvoke("Hello", new AsyncCallback(Callback), d);
// Give the callback time to execute - otherwise the app
// may terminate before it is called
Thread.Sleep(1000);
}
static int PrintOut (string parameter)
{
Console.WriteLine(parameter);
return 5;
}
static void Callback (IAsyncResult ar)
{
TestDelegate d = (TestDelegate)ar.AsyncState;
Console.WriteLine ("Delegate returned {0}", d.EndInvoke(ar));
}
}

No comments:

Labels