c# - Is this the best way for status message display? -
is best way utilize status message displays 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 toolstripstatuslabel
) accessed method during whole application operation.
the above code works. message displayed on control 2 secs , goes away...
if in winforms, suspect, not work. allowed access ui controls main windows message thread, can reached using invoke
on control. update, while code work, because actual object manipulating thread not control
- in general in winforms, cross thread access not allowed.
also, new thread each status seems overkill. yes, thread going disposed gc @ point, threads expensive resource create, , code creates 1 each status change. better approach use built-in thread pool (where acquire processing time on long-lived thread pool managed framework), or using timer
, designed running code @ specified intervals.
how changing text, use timer hide again after desired time ?
here solution using 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 timer constructed already, , has it's tick
event hooked statustimer_elapsed
event. reason why system.windows.forms.timer
class suited this, timer event raised on ui thread, meaning not have worry cross-thread access controls.
disclaimer: thought above sample without using compiler, might need tweaked.
Comments
Post a Comment