By using delegates, we can make Asynchronous method.
Below is a class named DataCache, which may periodically need to write its cache to a file. The class contains a method named FlushToDisk to simulate this operation.
public int FlushToDisk(string fileName)
// simulate a long operation Thread.Sleep(4000);
Since writing to disk is an expensive operation, we would like execute the FlushToDisk method asynchronously. The next example defines the CacheFlusher delegate and then uses it to call the DataCache object’s FlushToDisk method asynchronously.
static void Main(string args)
// create the object
DataCache cache = new DataCache();
// create the delegate
CacheFlusher flusher = new CacheFlusher(cache.FlushToDisk);
// call the delegate asynchronously
flusher.BeginInvoke("data.dat", new AsyncCallback(CallbackMethod), flusher);
// wait to exit
Console.WriteLine("Press enter to exit");
static void CallbackMethod(IAsyncResult result)
// get the delegate that was used to call that
CacheFlusher flusher = (CacheFlusher) result.AsyncState;
// get the return value from that method call
int returnValue = flusher.EndInvoke(result);
Console.WriteLine("The result was " + returnValue);
If you run this example you will see that the line “Press Enter to Exit” will be displayed in the console window, followed by the output from CallbackMethod. This is because the Main method calls BeginInvoke and continues processing, displaying its own output without waiting for the CacheFlusher delegate to finish. Later, when the asynchronous operation is complete, the delegate calls the CallbackMethod, which writes its output to the screen.
Asked In: Many Interviews |