I have recently been working on an application where I wanted to display the progress of another thread in the status bar via the ToolStripProgressBar
control that is contained in the StatusBar
control. Before I attempted to add this code I originally had the code changing the text of a ToolStripStatusLabel
control and to do this I used the Invoke method with delegates and everything worked fine. However, I found that when I attempted this with the ToolStripProgressBar
the call to the status bar's Invoke
method failed without a notification (no error, no exception, nothing). What I have since learned is that to use a progress bar in this way I had to use a BackgroundWorker
control. So my code works but I don't understand why I couldn't use the Invoke
method that already seemed to work.
Some examples of what worked and what didn't:
This worked
public delegate void changeStatusMessage(String message);
public changeStatusMessage changeStatusMessageDelegate;
public void changeStatusMessageMethod(String message){
if(statusbar.InvokeRequired){
statusbar.Invoke(changeStatusMessageDelegate, new Object[] {message});
}else{
toolstripLabel.Text = message;
}
}
This did not work
public delegate void incrementProgressBar(int value);
public incrementProgressBar incrementProgressBarDelegate;
public void incrementProgressBarMethod(int value){
if(statusbar.InvokeRequired){
statusbar.Invoke(incrementProgressBarDelegate, new Object[] {value});
}else{
toolstripProgress.Increment(value);
}
}
In the example that didn't work the InvokeRequired
property is true so the Invoke
method is called and then nothing happens. Where as I expected it to call the incrementProgressBarMethod
again this time where InvokeRequired
is false and thus allowing the Increment
method to fire.
I would really like to know why this doesn't work. As I said I have already retooled to use a BackgroundWorker
, I just want an explanation.