Game Development Reference
Another problem occurs when the application performs a long-running task but does
not provide any control to the user during this period. Many times these tasks are
developed to execute in entirety and then return, maybe updating the progress and dis-
playing it to the user, but the user will still not be able to interact with the application
until the task completes. This can lead to a few problems, such as the user being unable
to cancel the task if the need arises, and keeping the user from taking advantage of
other application features that logically should be available during the long process.
While performing a long task, you should make sure the application informs the
user of the progress by periodically updating the window with a progress bar or
similar control. Let the user know that the application is executing normally and
that the task is progressing. Additionally, you should also support interaction by
the user or the ability to access logical features while the task is processing.
For years, one of the most difficult and time-consuming tasks in Windows pro-
gramming has been the development and debugging of multi-threaded solutions.
Developers using .NET typically write asynchronous code using an asynchronous
pattern that returns an IAsyncResult using Begin and End methods. Otherwise,
developers use delegates or an explicit threading technique such as thread pools.
Some developers even resort to writing custom threading systems for various rea-
sons, despite the pain and suffering that occurs during the development of such
solutions. Generally, it is better to have an intrinsic approach, based on infrastruc-
ture, than to build a custom approach from the ground up. Additional patterns
have been introduced in version 2.0 of the .NET framework. One of these new pat-
terns is AsyncOperationManager and AsyncOperationFactory , coupled with a set of
custom events and delegates. While this approach is fairly straightforward to use,
advanced tasks will not benefit from this new mechanism.
An excellent component introduced in .NET 2.0 is the BackgroundWorker class,
which is a convenient way to start and monitor asynchronous operations, with the
ability to cancel the operation and report progress to the user. This chapter shows
how to use BackgroundWorker safely and how to correctly marshal control between
the worker thread and the Windows Forms thread in a thread-safe fashion. The
demo presented in this solution calculates Fibonacci numbers, and will be used to
introduce you to the implementation details of BackgroundWorker .
Implementing the Worker Logic
The first step is to create a new BackgroundWorker object, specify the appropriate set-
tings, and rig the instance up with event handlers. Table 37.1 shows the important
members of the BackgroundWorker class.