This post has 342 words. It will take approximately 3 minutes, 25 secondes for reading it.
I’ve been playing around with an application that changes subcontrols of the StatusBar in .NET (using C#). One of the first things I learned about .NET and Windows Forms is that if you do anything cross-thread you had better use an Invoke method with delegates or you get annoying errors. Now the first control I added to the StatusBar is a ToolStripStatusLabel which basically is a label in the status bar (duh). If I want to change the text of the label then I have to do an invoke, but the invoke is not on the label itself but on the parent (i.e. the status bar) so my code to change the label looks something like this:
public void changeStatusMethod(String message)
{
if (statusbar.InvokeRequired)
{
statusbar.Invoke(changeStatusDelegate,new object[] {message});
}
else
{
lblNumIncoming.Text = message;
}
}
Now this works and it works exactly as I expected. So the next thing I wanted to do is work with a ToolStripProgressBar which is (I’m sure you’ve guessed it already) a progress bar that appears in the status bar (wow amazing huh?). Now I wanted to increment and basically control this progress bar from another thread (yep just like every other application that displays a progress bar). So I assumed the code would look like this:
public void updateProgMethod(int value)
{
if (statusbar.InvokeRequired)
{
statusbar.Invoke(updateProgDelegate, new Object[] { value });
}
else
{
if (tsProg.Value + value < tsProg.Maximum)
{
tsProg.Increment(value);
}
}
}
GUESS WHAT?!? This doesn’t work! What happens is that the invoke is called and then nothing happens. The delegate does not call the method again to actually do the work? So naturally I did a bit of research, and no one seems to explain why this doesn’t work. It seems most everyone prefers to do things with a BackgroundWorker. While I’ve since refactored my code to use a BackgroundWorker, it isn’t really what I wanted. Now if anyone can properly explain why the invoke doesn’t work but a BackgroundWorker does work, you will win the World!