If this is in WinForms, as I suspect, this is not likely to work. You are only allowed to access the UI controls from the main windows message thread, which can be reached by using Invoke
on a Control. Update, while your code does work, this is because the actual object you are manipulating from the thread is not a Control
- in general in WinForms, cross thread access is not allowed.
Also, a new thread for each status seems overkill. Yes, the thread is going to be disposed by the GC at some point, but Threads are an expensive resource to create, and your code creates one for each status change. A much better approach is to use the built-in thread pool (where you acquire processing time on a long-lived thread from a pool managed by the framework), or using a Timer
, which is designed for running code at specified intervals.
How about changing the text, then use a Timer to hide it again after the desired time ?
Here is a solution using a Timer
:
private void SetStatus(Color _color, string _msg)
{
stsStatusMsg.ForeColor = _color;
stsStatusMsg.Text = _msg;
timer.Start();
}
private void StatusTimer_Elapsed(object sender, EventArgs e)
{
stsStatusMsg.Text = "";
timer.Stop();
}
The above code assumes that the timer is constructed already, and that it has it's Tick
event hooked up to the StatusTimer_Elapsed
event. The reason why the System.Windows.Forms.Timer
class is well suited for this, is that the timer event is raised on the UI thread, meaning you will not have to worry about cross-thread access to the controls.
Disclaimer: I just thought up the above sample without using a compiler, it might need to be tweaked.