views:

50

answers:

3

There are two objects. The Windows Form with a button and a progress bar, and another object that handles an algorithm.

In the algorithm object there is an event, and a property. The event is ProgressChanged, and the property is Progress (which is an int).

In the calling window, the button starts off a set of steps in the algorithm object. As each step (or substeps) occurs, the ProgressChanged event fires, and in the window there is an event handler that essentially increments the progress bar relative to the Progress property.

The problem I am running into is that because the algorithm has a possibility (and high liklihood) of running a relatively long time, I need to move it into it's own background thread and push the event back up to the window.

My issue is that I'm not completely sure what I'm doing when it comes to multi-threading. I've looked at Control.Invoke and I'm a little lost.

Can someone point me in the right direction?

+3  A: 

Use a Backgroundworker. It has a ReportProgress method + event to let you run the progressbar w/o worrying about Invoke.

Henk Holterman
That looks to be the solution. Thanks!
Steve Syfuhs
A: 

As the other poster says, use a BackgroundWorker component. Explanation and sample code on: http://ondotnet.com/pub/a/dotnet/2005/07/25/backgroundworker.html

-Oisin

x0n
+1  A: 

Here's an example of how to use Invoke to change to the UI thread, where it is safe to access controls:

// In some form method, setup the event handler
algorithm.ProgressChanged += new EventHandler(AlgorithmProgressChanged);

private void AlgorithmProgressChanged(Object source, EventArgs args)
{
    if (this.InvokeRequired)
    {
        // Switch to the UI thread
        this.Invoke(new EventHandler(AlgorithmProgressChanged), source, args);
        return;
    }
    // It should be safe to set the progress beyond this point.
    progressBar.Value = algorithm.Progress;
}
Paul Williams