Sunday, February 13, 2011

BeginInvoke and EndInvoke Pattern.



Call a Method Asynchronously using Delegate



Now that you know how the BeginInvoke and EndInvoke methods of the Delegate class work, let us see the different ways/patterns available to use BeginInvoke() and EndInvoke() to make asynchronous calls



EndInvoke Pattern - In this pattern, we use BeginInvoke from the Main thread to call the method, then do some processing on the main thread and then call EndInvoke(). This is useful when you want to have the calling thread to continue processing at the same time the asynchronous call is executing. Here the EndInvoke() does not return until the asynchronous call has completed. In other words, the main thread waits till the asynchronous operation is complete.



WaitHandle – Using this technique, the main method calls the method asynchronously and waits for a WaitHandle before it calls EndInvoke().



Polling Pattern - In this pattern, the calling thread polls the other thread (doing async operation) periodically using the IAsyncResult object and checks whether the thread has completed. If not, it continues processing and checks the thread later. The application does not call EndInvoke() until it knows that the operation is complete. This pattern can be useful when you want your UI to be responsive, till the async operation completes.



Callback Pattern - In this pattern, the initial thread initiates the async call but does not wait or check to see if the thread that was called, has completed. This pattern can be useful if you not want to process the results of the async call in the main thread. Note: CallbackMethod would be called in the thread in which BeginInvoke is called ( a thread taken from ThreadPool).



Let us see an example of calling a method asynchronously using the EndInvoke Pattern














class SampleThree


{


public class AsyncDemo {





public string Work(int time, out int threadId) {


Thread.Sleep(time);


threadId = Thread.CurrentThread.ManagedThreadId;


string message = String.Format("My call time was {0}, with threaId:{1}", time.ToString(), threadId);


return message;


}





public delegate string DoWork(int time, out int threadId);


}





public class AsyncJob {





public static void Start() {





var asyncDemo = new AsyncDemo();


int threadId;


var doWorkDelegate = new AsyncDemo.DoWork(asyncDemo.Work);


var result = doWorkDelegate.BeginInvoke(5000, out threadId, null, null);




Thread.Sleep(0);


Console.WriteLine("Main thread {0} does some work.",


Thread.CurrentThread.ManagedThreadId);





var message = doWorkDelegate.EndInvoke(out threadId, result);


Console.WriteLine(message);


var hereNow = 0;


}


}





public class WaitHandleJob {


public static void Start()


{


var asyncDemo = new AsyncDemo();


int threadId;


var doWorkDelegate = new AsyncDemo.DoWork(asyncDemo.Work);


var result = doWorkDelegate.BeginInvoke(5000, out threadId, null, null);





Thread.Sleep(0);


Console.WriteLine("Main thread {0} does some work.",


Thread.CurrentThread.ManagedThreadId);





result.AsyncWaitHandle.WaitOne();


var message = doWorkDelegate.EndInvoke(out threadId, result);


Console.WriteLine(message);


var hereNow = 0;




}





}





public class PollingJob


{


public static void Start()


{


var asyncDemo = new AsyncDemo();


int threadId;


var doWorkDelegate = new AsyncDemo.DoWork(asyncDemo.Work);


var result = doWorkDelegate.BeginInvoke(5000, out threadId, null, null);





Thread.Sleep(0);


Console.WriteLine("Main thread {0} does some work.",


Thread.CurrentThread.ManagedThreadId);





while (result.IsCompleted == false)


{


Thread.Sleep(50);


Console.Write(".");


}





result.AsyncWaitHandle.WaitOne();


var message = doWorkDelegate.EndInvoke(out threadId, result);


Console.WriteLine(message);


var hereNow = 0;





}





}





public class CallBackJob {





public static void Start()


{


var asyncDemo = new AsyncDemo();


int threadId;


var doWorkDelegate = new AsyncDemo.DoWork(asyncDemo.Work);


var result = doWorkDelegate.BeginInvoke(5000, out threadId, new AsyncCallback(CallbackMethod),


"The call executed on thread {0}, with return value \"{1}\".");





Thread.Sleep(0);


Console.WriteLine("Main thread {0} does some work.",


Thread.CurrentThread.ManagedThreadId);





}





static void CallbackMethod(IAsyncResult ar)


{


// Retrieve the delegate.


AsyncResult result = (AsyncResult)ar;


var caller = (HornetConsole._Practice.Threads.SampleThree.AsyncDemo.DoWork)result.AsyncDelegate;





// Retrieve the format string that was passed as state


// information.


string formatString = (string)ar.AsyncState;





// Define a variable to receive the value of the out parameter.


// If the parameter were ref rather than out then it would have to


// be a class-level field so it could also be passed to BeginInvoke.


int threadId = 0;





// Call EndInvoke to retrieve the results.


string returnValue = caller.EndInvoke(out threadId, ar);





// Use the format string to format the output message.


Console.WriteLine(formatString, threadId, returnValue);


}





}


}



SafeInvoke.. will all checks and bounds.



public static void SafeInvoke(this Control uiElement, Action updater, bool forceSynchronous) { if (uiElement == null) { throw new ArgumentNullException("uiElement"); } if (uiElement.InvokeRequired) { if (forceSynchronous) { uiElement.Invoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); }); } else { uiElement.BeginInvoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); }); } } else { if (!uiElement.IsHandleCreated) { // Do nothing if the handle isn't created already. The user's responsible // for ensuring that the handle they give us exists. return; } if (uiElement.IsDisposed) { throw new ObjectDisposedException("Control is already disposed."); } updater(); } }

No comments:

Post a Comment