Breaking from a loop with button click - C#

22,624

Solution 1

Use a background worker to do your work. You can use the cancellation feature to break out of it when you're done. Your loop as you have it will block the UI thread when executed syncronously, which is why your GUI becomes unresponsive. Note if you do any interaction with the UI in the do work delegate, you need to marshal back onto the UI thread (via invoke for example).

private BackgroundWorker _worker = null;

private void goButton_Click(object sender, EventArgs e)
{
    _worker = new BackgroundWorker();
    _worker.WorkerSupportsCancellation = true;

    _worker.DoWork += new DoWorkEventHandler((state, args) =>
    {
        do
        {
            if (_worker.CancellationPending)                
                break;

            Console.WriteLine("Hello, world");

        } while (true);
    });

    _worker.RunWorkerAsync();
    goButton.Enabled = false;
    stopButton.Enabled = true;
}

private void stopButton_Click(object sender, EventArgs e)
{
    stopButton.Enabled = false;
    goButton.Enabled = true;
    _worker.CancelAsync();
}

Update 2019: BackgroundWorker is now largely obsolete, replaced by the async/await feature in later versions of C# which is easier to use. Here is an example of how to achieve the same thing using that feature:

private CancellationTokenSource _canceller;

private async void goButton_Click(object sender, EventArgs e)
{
    goButton.Enabled = false;
    stopButton.Enabled = true;

    _canceller = new CancellationTokenSource();
    await Task.Run(() =>
    {
        do
        {
            Console.WriteLine("Hello, world");
            if (_canceller.Token.IsCancellationRequested)
                break;

        } while (true);
    });

    _canceller.Dispose();
    goButton.Enabled = true;
    stopButton.Enabled = false;
}

private void stopButton_Click(object sender, EventArgs e)
{
    _canceller.Cancel();
}

Solution 2

There's one important thing to remember:

While your code is being executed, the user cannot interact with your user interface.

That means: You first need to exit the loop (i.e. return from the Spam method), and then the user can click Button2.

That's a hard truth, because it means you cannot write the code in the way you wanted to. Fortunately, there are a few ways to work around that:

  • Don't use a loop. Use some kind of timer to do the "spamming". Button1 starts the timer, Button2 stops it. What kind of timer is available depends on the user interface library you use (WinForms has a Timer, WPF has a DispatcherTimer).

  • Do the "spamming" in a background thread. This will allow your user interface to stay responsive, and you can communicate with the background thread, for example, by setting a volatile Boolean. This, however, is an advanced topic (and can quickly lead to complex synchronization issues), so I suggest that you try the other option first.

Share:
22,624
Hellooo123
Author by

Hellooo123

Updated on June 06, 2020

Comments

  • Hellooo123
    Hellooo123 almost 4 years

    I have a question regarding looping with button click event, I've tried many methods & searched many pages in search for a simple answer for the past hour, but the truth is each answer just looks like alien code, probably because I'm still very new to developing.

    Here's a simplified version of what I'm trying to do :

    private string Message = "Hello";
    
    private void Spam(bool loop)
    {
        if (loop == true)
        {
            while (loop == true)
            {
                MessageBox.Show(Message);
            }
        }
        else { MessageBox.Show("Spamming has stopped !! "); }
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
        Spam(true);
    }
    private void button2_Click(object sender, EventArgs e)
    {
        Spam(false);
    }
    

    Obviously this isn't my API, or it'd be a useless thing to invent, however, the code itself is long & you guys always ask for "relevant code" (No disrespect), so there it is.

    My problem : Breaking out of the spam loop upon clicking button 2, the code to me looks decent enough for the API to figure out, but each time button 1 is clicked, the API freezes.

  • Hellooo123
    Hellooo123 over 9 years
    Changed MessageBox to label1.Text, freezes, while(loop) is always true, no chance for button 2 click event
  • Hellooo123
    Hellooo123 over 9 years
    I've seen background threads used in several API's that I recently started working with, so it's definitely something I should concentrate on, thanks for this heads up, very useful
  • Hellooo123
    Hellooo123 over 9 years
    Excellent answer, and a great introduction to back-ground workers. You've made my day, nice job.
  • boctulus
    boctulus over 9 years
    Anybody know how to pass an anonymous object o RunWorkerAsync() ? something like backgroundWorker1.RunWorkerAsync(new { start = 108, end = 502404 });
  • steve16351
    steve16351 over 9 years
    @Boctulus, as you have it should be fine.. in the DoWork method, it should show up in the DoWorkEventArgs parameter (args in the example above). Then you can just use your object after getting a reference like this, dynamic anon = args.Argument;.
  • boctulus
    boctulus over 9 years
    Thank you very much @steve16351 ... you save me :)
  • vr_driver
    vr_driver almost 4 years
    This latest update seems to be only available in .net 4.5+