Is this the best way to utilize a status message that displays for some time?
private void SetStatus(Color _color, string _msg)
{
System.Threading.Thread t = new System.Threading.Thread(() =>
{
stsStatusMsg.ForeColor = _color;
stsStatusMsg.Text = _msg;
System.Threading.Thread.Sleep(2000);
stsStatusMsg.Text = "";
});
t.Start();
}
Example of calling it:
SetStatus(Color.Red, AppMessages["msgALREADYIN"]);
stsStatusMsg (which is a ToolStripStatusLabel) is accessed only by this method during the whole application operation.
The above code actually works. The message is displayed on the control for 2 secs and then goes away…
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
Invokeon a Control. Update, while your code does work, this is because the actual object you are manipulating from the thread is not aControl– 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:The above code assumes that the timer is constructed already, and that it has it’s
Tickevent hooked up to theStatusTimer_Elapsedevent. The reason why theSystem.Windows.Forms.Timerclass 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.