I need to generate two random numbers every X seconds on a WinForms application, but am unable to. My goal is generating two numbers every 2-1 seconds, to show them in the WinForms. The only way my code works is when I put a MessageBox.Show() before generating the two random numbers. Please, explain me the why like I'm five.
What I tried, with my code:
public partial class FrmPrincipal : Form
{
private int temperatura = 0;
private int umidade = 0;
public FrmPrincipal()
{
InitializeComponent();
}
private void cadastrarNovoToolStripMenuItem_Click(object sender, EventArgs e)
{
FrmCadLote frmCadLote = new FrmCadLote();
frmCadLote.ShowDialog();
}
private void atualizarToolStripMenuItem_Click(object sender, EventArgs e)
{
FrmAtualizacaoLote frmAtualizacaoLote = new FrmAtualizacaoLote();
frmAtualizacaoLote.ShowDialog();
}
private void excluirToolStripMenuItem_Click(object sender, EventArgs e)
{
FrmExclusaoLote frmExclusaoLote = new FrmExclusaoLote();
frmExclusaoLote.ShowDialog();
}
private void consultarToolStripMenuItem_Click(object sender, EventArgs e)
{
FrmConsultaLote frmConsultaLote = new FrmConsultaLote();
frmConsultaLote.ShowDialog();
}
private void btnSensores_Click(object sender, EventArgs e)
{
ativaSensor();
}
public void ativaSensor()
{
Random rnd = new Random();
Boolean sensorAtivo = false;
if (!sensorAtivo)
{
// It only works when I enable this MessageBox
MessageBox.Show("ok");
this.temperatura = rnd.Next(0, 40);
this.umidade = rnd.Next(0, 100);
lblUmidade.Text = umidade.ToString();
lblTemperatura.Text = temperatura.ToString();
Thread.Sleep(1000);
ativaSensor();
}
}
}