[英]“drag and drop to form” timer in visual studio express 2013 doesn't work
I have no idea why this code does not work. 我不知道为什么这段代码不起作用。
The timer just seams to freeze everything. 计时器只是接缝冻结一切。 As far as I know, the timer is sent to a newly created thread.
据我所知,计时器被发送到新创建的线程。 I've tried locking on tick, but no luck.
我试过锁定勾号,但没有运气。
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public int CountUp = 0;
public Form1()
{
InitializeComponent();
label1.Text = "Click To Start Timer";
timer1.Enabled = false;
timer1.Stop();
timer1.Interval = 1000;
}
private void button1_Click(object sender, EventArgs e)
{
bool Toggled = false;
if (!Toggled)
{
timer1.Enabled = true;
Toggled = true;
}
else
{
timer1.Enabled = false;
Toggled = false;
label1.Text = "Timer Stopped";
CountUp = 0;
}
while(Toggled){
label1.Text = "Timer1 Running";
}
}
private void timer1_Tick(object sender, EventArgs e)
{
//lock (label2.Text) <- froze the program immediately
//{
// CountUp++;
// string CurrentTime = CountUp.ToString();
// label2.Text = CurrentTime;
//}
CountUp++;
string CurrentTime = CountUp.ToString();
label2.Text = CurrentTime;
//CurrentTime = timer1.ToString() = Garbage & freeze.
}
}
}
Any suggestions? 有什么建议么? It may be the key to solving this question .
这可能是解决这个问题的关键。
The while(Toggled){ .. }
code will freeze the interface and hang the program as it blocks the UI thread. while(Toggled){ .. }
代码将冻结接口并挂起程序,因为它阻止了UI线程。 However, the Forms.Timer , which relies on the UI event queue being processed, will never fire due to the blocking loop - as such, the flag variable will never be "reset". 但是,依赖于正在处理的UI事件队列的Forms.Timer将永远不会因阻塞循环而触发 - 因此,标志变量永远不会被“重置”。
While one of the threaded timers could be used, it would still result in an un-responsive UI. 虽然可以使用螺纹计时器之一,它仍然会导致未响应的用户界面。 The solution is to design [WinForm] programs to react to events , such as when the timer starts and when it stops 1 .
解决方案是设计[WinForm]程序以响应事件 ,例如计时器启动时和停止1时 。
1 There are actually no start/stop events per-se, but do the actions when the timer is started or stopped by the code. 1实际上本身没有启动/停止事件,但是在代码启动或停止定时器时执行操作。 For example,
例如,
private void button1_Click(object sender, EventArgs e)
{
if (!timer1.Enabled) {
CountUp = 0;
timer1.Enabled = true;
label1.Text = "Timer1 Running";
} else {
timer1.Enabled = false;
label1.Text = "Timer1 Stopped (Manual)";
}
}
// Later on, when a tick occurs and the timer should end..
// The timer callback runs on the UI thread it was created on.
private void timer1_Tick(object sender, EventArgs e)
{
CountUp++;
if (CountUp > 10) {
timer1.Enabled = false;
label1.Text = "Timer1 Stopped (Time up)";
}
}
There is no need to use lock
at all because all of the code should be running on the UI thread. 根本不需要使用
lock
,因为所有代码都应该在UI线程上运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.