Browse DevX
Sign up for e-mail newsletters from DevX


Build Better UIs with the Asynchronous Support in .NET 2.0  : Page 4

Good user interfaces let users keep working as seamlessly as possible while an application performs long background processing tasks. While .NET 1.0 certainly simplified the process of launching and managing multiple threads in Windows applications, you had to write much of the infrastructure yourself. In contrast, .NET 2.0 adds direct framework support for asynchronously fetching data and performing background tasks.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Asynchronous Background Processing
Author Note's: You'll find the sample code for this section in the BackGroundProcessing.sln project in the downloadable source.

In addition to asynchronous SQL query support, the .NET 2.0 framework provides a new Asynchronous pattern for components supported by a set of new infrastructure classes such as AsyncOperationManager, and AsyncOperationFactory along with a set of custom delegate and event declarations. This pattern works fairly intuitively for simple tasks such as reporting execution progress, canceling already-begun tasks, etc.; however, you need to delve more deeply into the infrastructure for more advanced tasks. For these, you use the BackGroundWorker class in the System.ComponentModel namespace. BackGroundWorker runs an assigned task on a separate thread and provides a set of events and methods to start and monitor asynchronous operations, with options for querying the task status and canceling the task.

Implementing a very basic file search task in a Windows Forms application provides an ideal example, because it's a easy to understand, fulfills a relatively common need, takes a considerable amount of time to complete—and you would want users to be able to continue working while the search is in progress. This simple application accepts an input query string, and performs a string search against a set of file names using the code FileInfo.Name.IndexOf("input")>0 for a set of directories, listing any matching files. Users expect such searches to operate in the background, without suspending the current application. In addition, users expect an option to stop the search at any time.

To start:
  1. Create a new Windows Forms project and open the design view of the default form.
  2. Add controls to the Form designer as shown in Figure 4.
  3. Figure 4. The File Searcher Interface: The figure shows how your default form should look after adding controls to create the File Searcher interface.
  4. Create a new class named ContentSearcher.vb, which wraps a BackGroundWorker object and contains the following code:

Private WithEvents searchFolders As _ System.ComponentModel.BackgroundWorker Public Delegate Sub FoundInfo(ByVal info As FileInfo) Public Delegate Sub ProcessCompleted( _ ByVal value As String) Private callback As FoundInfo Private callComplete As ProcessCompleted Public Sub New(ByVal Callmethod As FoundInfo, _ ByVal CallBackOnComplete As ProcessCompleted) searchFolders = New _ System.ComponentModel.BackgroundWorker callback = Callmethod Me.callComplete = CallBackOnComplete searchFolders.WorkerReportsProgress = True searchFolders.WorkerSupportsCancellation = True End Sub

The class declares the searchFolders BackGroundWorker instance using WithEvents to expose the object's event model. The constructor of the ContentSearcher class has two delegate references: one to make a callback to the client when it finds a matching file, named FoundInfo, and the other, called ProcessCompleted, to return string error and completion messages. You need to set the BackgroundWorker properties WorkerReportsProgress and WorkerSupportsCancellation to True to enable progress reporting and cancellation. Table 2 lists other important BackgroundWorker methods and events.

Table 2. BackgroundWorker Members: The table lists the most important BackgroundWorker properties and methods.




This method starts the process on a separate thread asynchronously.


This method cancels a progressing background task.


On raising CancelAsync, this property value is set to True, requesting cancellation of a task.


Get/Sets a Boolean value to indicate if the worker class can support progress updates.


Get/Sets a Boolean value to indicate if the worker class can support cancellation of the current task in progress.


You can set a value to indicate the progress of the operation. The overloaded option lets you specify a userState object.


This event is invoked by calling RunWorkerAsync


Fires when the background operation is cancelled, completed, or an exception is thrown.


Fires whenever the ReportProgress property is set. The event can retrieve the userState in its overloaded parameter when set by the ReportProgress method.

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