C# 重复代码执行
我试图在预定义的时间过后重复代码执行,我不想使用线程来搞乱事情。下面的代码是一个好的实践吗C# 重复代码执行,c#,C#,我试图在预定义的时间过后重复代码执行,我不想使用线程来搞乱事情。下面的代码是一个好的实践吗 Stopwatch sw = new Stopwatch(); // sw constructor EXIT: // Here I have my code sw.Start(); while (sw.ElapsedMilliseconds < 100000) { // do nothing, just wait } System.M
Stopwatch sw = new Stopwatch(); // sw constructor
EXIT:
// Here I have my code
sw.Start();
while (sw.ElapsedMilliseconds < 100000)
{
// do nothing, just wait
}
System.Media.SystemSounds.Beep.Play(); // for test
sw.Stop();
goto EXIT;
Stopwatch sw=新秒表();//软件构造器
出口:
//这是我的密码
sw.Start();
同时(sw.ElapsedMilliseconds<100000)
{
//什么也不做,只是等待
}
System.Media.SystemSounds.Beep.Play();//测试
sw.Stop();
转到出口;
使用计时器代替标签和秒表
。你在忙着等待,把CPU卡在了一个很紧的循环中
启动计时器,给它一个触发间隔(100000毫秒),然后在事件处理程序中为勾选
事件运行代码
请参阅MSDN杂志。使用计时器代替标签和秒表。你在忙着等待,把CPU卡在了一个很紧的循环中
启动计时器,给它一个触发间隔(100000毫秒),然后在事件处理程序中为勾选
事件运行代码
请参阅MSDN杂志。您可以按照Oded的建议使用计时器:
public partial class TestTimerClass : Form
{
Timer timer1 = new Timer(); // Make the timer available for this class.
public TestTimerClass()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Tick += timer1_Tick; // Assign the tick event
timer1.Interval = 1000; // Set the interval of the timer in ms (1000 ms = 1 sec)
timer1.Start(); // Start the timer
}
void timer1_Tick(object sender, EventArgs e)
{
System.Media.SystemSounds.Beep.Play();
timer1.Stop(); // Stop the timer (remove this if you want to loop the timer)
}
}
编辑:只是想告诉你如果你不知道如何制作一个简单的计时器:)你可以使用Oded建议的计时器:
public partial class TestTimerClass : Form
{
Timer timer1 = new Timer(); // Make the timer available for this class.
public TestTimerClass()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Tick += timer1_Tick; // Assign the tick event
timer1.Interval = 1000; // Set the interval of the timer in ms (1000 ms = 1 sec)
timer1.Start(); // Start the timer
}
void timer1_Tick(object sender, EventArgs e)
{
System.Media.SystemSounds.Beep.Play();
timer1.Stop(); // Stop the timer (remove this if you want to loop the timer)
}
}
编辑:只是想告诉你,如果你不知道如何制作一个简单的计时器:)坏习惯的好例子;)不良做法的好例子;)