Sunday 1 September 2013

C# Delegates Series Part 4 - Delegates can be used to Invoke methods asynchronously

Below is the reference of all posts in this series

  1. C# Delegates Series Part 1 - Overview
  2. C# Delegates Series Part 2 - Delegates allows methods to be passed as parameters
  3. C# Delegates Series Part 3 - Delegates can be used to define event handlers and event handling mechanism
  4. C# Delegates Series Part 4 - Delegates can be used to Invoke methods asynchronously

When Main UI thread invokes some method, main thread waits until that method completes and then continues with rest of the processing. This might turn out expensive in some scenarios where called method takes more time to execute or communicates with third party service or downloads a large file. This would make application less responsive. In such cases, delegates can be useful to call these methods asynchronously.

Note: BackgroundWorker class in C# is another powerful way to execute code asynchronously. BackgroundWorker also supports reporting progress, cancelling the thread and so on.

There are 4 different ways to invoke methods asynchronously using delegates with some variations.

1.   Call a Method Asynchronously using Delegate BeginInvoke and EndInvoke: In this approach, main thread will invoke other method using delegate BeginInvoke method. BeginInvoke initiates asynchronous call on separate thread and returns immediately so that main thread can continue with rest of the processing. Main thread can later call EndInvoke method to end the thread and return the result. If main thread has call EndInvoke and if method has not completed the execution, then main thread will wait for method to complete.

2.   Call a Method Asynchronously using WaitHandle: In this approach, the main thread will invoke other method using delegate BeginInvoke method, waits for a WaitHandle and then call EndInvoke().

3.   Call a Method Asynchronously in .NET using Polling: In this approach, Main thread will invoke other method using delegate BeginInvoke, continue with rest of the processing and periodically poll other thread/method (using IAsyncResult IsCompleted property) to check if method has completed the execution. During polling, if main thread finds that method has completed the execution (IsCompleted = true), delegate EndInvoke will be used to end the thread and return the result from method.

4.   Call a Method Asynchronously in .NET using Callback: In this approach, main thread will invoke other method using delegate BeginInvoke along with callback method passed as parameter and continue with rest processing. When other method completes the execution, it invokes callback method which is passed as delegate reference. This callback method will then call delegate EndInvoke to end the thread and return the result from method.

MSDN article provides a good description of these approaches along with examples.

No comments:

Post a Comment