如何使用foreach终止并重新启动

这是我的代码,但是stop = true之后,再次stop = false并且不会重新循环

    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;
    }
HU9694 回答:如何使用foreach终止并重新启动

stop永远不会在代码中重置为false。每次单击button1时,使用新的CancellationToken可能会更好:

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();
}
,

您的代码中的问题是无法将stop重置为false

stop = false;移出循环(不执行任何操作),并将其放在button1_Click中循环外的任何位置。

本文链接:https://www.f2er.com/3167970.html

大家都在问