0

Is there any way to do any cycle and break it until another button in the WinForms is pressed ?

do
        {
            //Action
        } while ("Button Stop is pressed");
  • The right way of doing this: ["Async in 4.5: Enabling Progress and Cancellation in Async APIs"](http://blogs.msdn.com/b/dotnet/archive/2012/06/06/async-in-4-5-enabling-progress-and-cancellation-in-async-apis.aspx). – noseratio Apr 14 '14 at 07:17

2 Answers2

1

The best way that you can do this without blocking the gui is to make use of threads, for instance:

Thread t = new Thread (delegate() {
   while(true) {
     What you want to happen inside the loop in here;
     Thread.Sleep(500); // this is useful for keeping the headroom of the CPU
   }
});

Start the Thread this way:

t.Start();

When the stop button is pressed abort the thread this way:

t.Abort();

This keeps the gui alive.

Transcendent
  • 5,598
  • 4
  • 24
  • 47
  • @user3363472: You are very welcome, you can accept this (or other) answer if you'd like to – Transcendent Apr 14 '14 at 00:11
  • -1 for `Thread.Abort`, it's a terrible way of terminating a thread: http://stackoverflow.com/questions/421389/is-this-thread-abort-normal-and-safe – noseratio Apr 14 '14 at 07:16
0

There are two possible cases:

1-You are running that loop in the main thread, then the answer is no, if you block the main thread events will not fire and can't catch button click.

2-You are running that loop in a worker thread, in this case you can create a boolean outside the function set to true, check this boolean in your loop and set it to false in the click event of your button.

Gusman
  • 14,905
  • 2
  • 34
  • 50