c# winform中如何实现用随机数动态改变timer控件的Interval属性
没太明白啊!这个n是什么意思呢?Random r = new Random(); int n = r.Next(5, 10);
然后每次循环n-1是个什么思路,n为0的话m+1又是什么意思呢?是每5-10秒循环一次,不是每循环一次减1秒呀?是我理解的问题吗?能不能给个简单的代码呢!?
static Random r = new Random();
int n = r.Next(5, 11);
int m = 0;
private void timer1_Tick(object sender, EventArgs e)
{
n--;
if (n == 0)
{
Console.WriteLine("第"+m+"次循环已执行");
m++;
n = r.Next(5, 11);
}
if(m>=30)
{
Console.WriteLine("30次循环已经完成");
timer1.Enabled = false;
}
}
首先计时器可以实现,使用Thread.Sleep也是可以的。
不是使用Thread.Sleep不行的,是你在主线程执行了这个Thread.Sleep,你如果开一个子线程也是可以用Thread.Sleep实现的。
计时器实现方法楼上说的没毛病。下面给一个Thread.Sleep实现代码,开个子线程来循环,
private void Button4_Click(object sender, EventArgs e)
{
_state = true;
button4.Enabled = false;
Thread th = new Thread(Test);
th.IsBackground = true;
th.Start();
}
private void Button5_Click(object sender, EventArgs e)
{
_state = false;
button4.Enabled = true;
}
private void Test()
{
Random rd = new Random();
for (int i = 1; i <= 30; i++)
{
if (!_state)
{
break;
}
int time = rd.Next(5, 11);
Invoke(new Action(() =>
{
label5.Text = i.ToString();
label2.Text = time.ToString();
}));
for (int j = 0; j < time; j++)
{
if (!_state)
{
break;
}
Thread.Sleep(1000);
Invoke(new Action(() =>
{
label3.Text = (j + 1).ToString();
}));
}
Invoke(new Action(() =>
{
label5.Text = 0.ToString();
label2.Text = 0.ToString();
label3.Text = 0.ToString();
_state = false;
button4.Enabled = true;
}));
}
}