Dor*_*oro 2 c# windows multithreading timer task
我有一个winform应用程序,我需要使标签背面闪烁.我试图使用for循环和Thread.Sleep,但不起作用.感谢您的帮助和建议:
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
System.Threading.Thread.Sleep(1000); // Set fast to slow.
if (label1.BackColor == Color.Red)
label1.BackColor = Color.Transparent;
else
label1.BackColor = Color.Red;
}
}
Run Code Online (Sandbox Code Playgroud)
使用UI计时器,而不是为此任务休眠.你正在让主线程一直处于休眠状态,而你正在阻止用户输入.使用Thread.Sleep是几乎总是你正在做一些错误的标志.很Thread.Sleep正确的情况很少.具体来说,将UI线程置于睡眠状态永远不会正确.
Timer在表单上放置一个组件,并在Tick事件中,不断更改标签的背景颜色.
例如:
// Keeps track of the number of blinks
private int m_nBlinkCount = 0;
// ...
// tmrTimer is a component added to the form.
tmrTimer.Tick += new EventHandler(OnTimerTick);
m_nBlinkCount = 0;
tmrTimer.Interval = 1000; // 1 second interval
tmrTimer.Start();
// ...
private void OnTimerTick ( Object sender, EventArgs eventargs)
{
if (label1.BackColor == Color.Red)
label1.BackColor = Color.Transparent;
else
label1.BackColor = Color.Red;
m_nBlinkCount++;
if ( m_nBlinkCount >= 10 )
tmrTimer.Stop ();
}
Run Code Online (Sandbox Code Playgroud)