Handle Asynchronous Tasks Safely
One of .NET's most impressive features is its extensive support for multithreaded programming. However, as most programmers discover at some point in their lives, multithreaded programming isn't necessarily easy.
Note
Need to conduct a time-consuming task in the background without dealing with threading issues? The new BackgroundWorker class makes it easy.
One of the main challenges with Windows applications is that it's
not safe to modify a form or control from a background thread, which
means that after your background task is finished, there's no
straightforward way to update your application's interface. You can use
the Control.Invoke( )
method to
marshal a method to the correct thread, but other problems then appear,
such as transferring the information you need to make the update.
Fortunately, all of these headaches can be avoided thanks to the new
BackgroundWorker
component.
How do I do that?
The BackgroundWorker
component gives you a foolproof way to run a time-consuming task on a
separate, dedicated thread. This ensures that your application
interface remains responsive, and it allows your code to carry out
other tasks in the foreground. Best of all, the underlying
complexities of multithreaded programming are hidden. Once the
background process is complete, you simply handle an event, which
fires on the main thread. In addition, the BackgroundWorker
supports progress reporting
and canceling.
You can either create a BackgroundWorker
object ...
Get Visual Basic 2005: A Developer's Notebook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.