user11603749
user11603749

Reputation: 49

How to terminate and restart using foreach

Here is my code, but after stop = true, once again stop = false and will not re-circulate

    bool stop = false;
    private void button1_Click(object sender, EventArgs e)
    {
        string filename = @"temp1.txt";
        int n = 5;
        foreach (var line in File.ReadLines(filename).AsParallel().WithDegreeOfParallelism(n))
        {
            textBox1.Text = line;

            if (stop == true)
            {
                break;
            }
            stop = false;
        }
    }

    private void button4_Click(object sender, EventArgs e)
    {
        stop = true;
    }

Upvotes: 1

Views: 132

Answers (2)

phuzi
phuzi

Reputation: 13060

stop never gets reset to false in your code. You may be better off using a new CancellationToken each time button1 is clicked:

private CancellationTokenSource cancellationTokenSource;

private void button1_Click(object sender, EventArgs e)
{
    // create a new CancellationTokenSource and Token for this event
    cancellationTokenSource = new CancellationTokenSource();
    var cancellationToken = cancellationTokenSource.Token;

    string filename = @"temp1.txt";
    int n = 5;
    foreach (var line in File.ReadLines(filename).AsParallel().WithDegreeOfParallelism(n))
    {
        textBox1.Text = line;

        // Check if token has had a requested cancellation.
        if (cancellationToken.IsCancellationRequested)
            break;
    }
}

private void button4_Click(object sender, EventArgs e)
{
    if (cancellationTokenSource != null)
        cancellationTokenSource.Cancel();
}

Upvotes: 2

Robin Bennett
Robin Bennett

Reputation: 3231

The problem in your code is that there's no way for stop to be reset to false.

Take stop = false; out of the loop (where it's doing nothing) and put it anywhere outside the loop in button1_Click.

Upvotes: 1

Related Questions