Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Asynchronous Windows Forms Programming

Learn how to implement BackgroundWorker in Visual Studio .NET 2003 so you can benefit from its elegant programming model and transition transparently into Windows Forms 2.0 in the future.

indows Forms applications often require some sort of asynchronous invocation option. You rarely want to block the user interface while a lengthy operation executes in the background. Windows Forms pose a set of complicated design and implementation issues when it comes to asynchronous method invocation and multithreading due to the underlying Windows messages processing.

Although .NET does provide a uniform asynchronous invocation mechanism (described in my article, "Asynchronous .NET Programming," CoDe Magazine, May 2003) you cannot apply it as-is in a Windows Forms application. To address this problem, the next version of .NET (version 2.0, code-name Whidbey) provides a new component designed to ease the task of developing asynchronous Windows Forms applications. This article starts by describing the current asynchronous programming model available to Windows Forms developers. Then, not only does this article describe the Whidbey solution, it also provides a .NET 1.1 implementation of the solution so that you can take advantage of this superior programming model today and ease the transition into Windows Forms 2.0 in the future.

Windows Forms 1.1 and Asynchronous Execution
Developers commonly use a delegate to invoke an asynchronous method call in .NET. Each delegate provides a BeginInvoke() and EndInvoke() method. To invoke a method asynchronously, wrap it in a delegate and call BeginInvoke() on the delegate. The delegate will delegate the act of invoking the method to a thread from the thread pool, thus making it asynchronous towards the caller. You have several options available that let you deal with the method completion, from fire-and-forget to polling, but the most common option (and the one best fitting an event-driven application such as a Windows Forms application) is to use a callback method. When the asynchronous operation is completed, you can have .NET call back into a method you provide, where you can call EndInvoke() to harvest returned values or deal with errors. The thread from the thread pool will do the callback after it executes the method.

Windows Forms poses a set of complicated design and implementation issues when it comes to asynchronous method invocation and multithreading.
You identify the completion callback method using a delegate of the type AsyncCallback that you pass to the BeginInvoke() call used to dispatch the method asynchronously. You need to be familiar with a few additional details including how to gain access to the original delegate used to invoke the call from within the completion callback, but in general, the programming model just described is sufficient for most applications, except when it comes to Windows Forms. Why are Windows Forms the exception? First, any decent client application should want to display some progress or indication of the current status of the asynchronous task to the user. In fact, you may want to pass the progress report to multiple parties—you may need to update both the status bar and a progress bar. Second, you may want to allow the user to cancel the asynchronous method invocation in progress.

The crucial limiting factor in implementing these features is the thread affinity Windows Forms controls and forms have to the underlying thread that created them. All Windows messages are actually messages between threads, and each thread has its own message queue. Each and every thread message can only be processed on the thread it belongs to. When a thread creates a window, that window's messages are actually messages destined for the message queue of the creating thread. Consequently, all windows (such as forms and controls) can only process messages on the thread that created them. Method calls on forms and controls often result internally with posting of at least one such message.

In a simple Windows Forms application (such as the one created by the Visual Studio .NET application wizard), all forms and controls execute on the same thread—the primordial thread used to launch the application by calling Main()—so those forms and controls can freely call each other's methods.

When a Windows Forms window invokes a call asynchronously (using a delegate), that call executes on a worker thread from the thread pool, not the thread that created the window. The completion callback method is also executed on the worker thread. As a result, the completion callback method should never update the user interface directly because that would be calling a Windows Forms form or control on a different thread from the thread that created it. Similarly, progress reports triggered by the worker thread are not allowed to directly update controls such as a progress bar. In all these cases, you must marshal the call from the worker thread to the user interface thread. This is exactly what the ISynchronizeInvoke interface, defined in the System.ComponentModel namespace, is designed to do:

public interface ISynchronizeInvoke { object Invoke(Delegate method,object[] args); IAsyncResult BeginInvoke(Delegate method, object[] args); object EndInvoke(IAsyncResult result); bool InvokeRequired {get;} }

ISynchronizeInvoke provides a generic and standard mechanism for marshaling calls between threads.

For example, imagine a client on thread T1 and an object on thread T2. If the object implements ISynchronizeInvoke, the client on thread T1 can call ISynchronizeInvoke's Invoke() on the object. The implementation of Invoke() will block the calling thread (T1), marshal the call to T2, execute the call on T2, marshal the returned values to T1, and return control to the calling client on T1. Invoke() accepts a delegate targeting the method to invoke on T2, and a generic array of objects as parameters.

Because the call is marshaled to a different thread from that of the caller, you might want to be able to invoke it asynchronously. Microsoft created the BeginInvoke() and EndInvoke() methods to provide this functionality, but I won't address these methods in this article.

In addition, because ISynchronizeInvoke can be called on the same thread as the thread the caller tries to redirect the call to; the caller can check the InvokeRequired property. If it returns false, then the caller can call the object methods directly.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date