// The following method can also be simply put as the 3rd param to the BeginInvoke() using Lambda expr. static void WaitAWhileCompleted(IAsyncResult ar) { //The last parameter passed with the BeginInvoke() method can be read //here using ar.AsyncState. With the WaitAWhileDelegate you can invoke the EndInvoke method to //get the result. WaitAWhileDelegate d2 = ar.AsyncState as WaitAWhileDelegate; int result = d2.EndInvoke(ar); returnString += "\nResult: " + result.ToString(); //With a callback method, you need to pay attention to the fact that this method is //invoked from the thread of the delegate and not from the main thread. }
// Now, using the Asynchronous Callback public static void AsyncCallWaitAWhile() { returnString = String.Empty; WaitAWhileDelegate d2 = WaitAWhile; //The AsyncCallback delegate (third parameter of BeginInvoke()) defines a parameter of IAsnycResult //and a void return type. Here, the address of the method WaitAWhileCompleted is assigned to the third //parameter that fulfills the requirements of the AsyncCallback delegate. With the last parameter, you //can pass any object for accessing it from the callback method. It is useful to pass the delegate instance //itself, so the callback method can use it to get the result of the asynchronous method. d2.BeginInvoke(1, 3000, WaitAWhileCompleted, d2); returnString += "\nNow using the Asynchronous Callback:"; returnString += "\nWaiting for AsyncCallWaitAWhile()\nNumber passed = 1 and wait 3000ms\n"; int count = 0; for (int i = 0; i < 4; i++) { Thread.Sleep(1000); count++; } //count = count * 50; //Converting the count to represent the total ms passed. returnString += "\nSeconds Waited: " + count.ToString(); }