Monday, November 27, 2006

Running processes in background

Long story short: the BackgroundWorker object. Available in .NET 2.0
This is a Microsoft tutorial on using BackgroundWorker:
How to: Run an Operation in the Background
This is an older and more Windows Forms basic tutorial on multithreading:
Safe, Simple Multithreading in Windows Forms, Part 1
Safe, Simple Multithreading in Windows Forms, Part 2

Details:
BackgroundWorker has the DoWork, ProgressChanged, RunWorkerCompleted, and Disposed events. You need to assign at least one method for DoWork and one for RunWorkerCompleted, then run
bw.RunWorkerAsync(obj);
The DoWork method should do something like
e.Result=BackgroundOperation(obj);
while the RunWorkerCompleted method should do anything related to the GUI. There is also a CancelAsync() method, to try to stop a background operation.

Also, here is an article about a possible bug in BackgroundWorker, but I haven't replicated it on my computer.

0 comments: