If System.Threading.Thread.Sleep (1000) is used in a loop, the entire program is paused. I need to, during a pause in the loop, I can click on the Windows Forms buttons.

Reported as a duplicate by rdorn , Pavel Mayorov c # Feb 14 '18 at 1:34 pm

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • While pressing the button, I will exit the loop. - Login
  • Maybe you can use a better Timer at 1000 ms intervals? - Zergatul
  • Which of the timers? I can't use them, I can't find documentation and examples. - Login
  • Call the asychron method. The form will not crash, but System.Threading.Thread.Sleep (1000) sounds ((((Why do you need it at all? - isaikinvv
  • one
    Here is an example . - Bulson

1 answer 1

A simple example of starting a timer and then using it. The first button starts the timer, which increases i. The second button is to place i in the field. This way you can solve your problem. The program will not hang.

public partial class Form1 : Form { public Form1() { InitializeComponent(); } int i = 0; private void button1_Click(object sender, EventArgs e) { timer1.Interval = 1000; timer1.Enabled = true; } private void button2_Click(object sender, EventArgs e) { textBox1.Text = i.ToString(); } private void timer1_Tick(object sender, EventArgs e) { i++; } } 

}

UPD In your case, there will not be a cycle, but the necessary code will be called in the timer itself (for example, there will be a call to a function that you previously had in the cycle)

To stop the loop, you can use timer1.Enabled = false; which is called when a button is pressed