c# - 如何使用 foreach 终止和重新启动

标签 c# 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;
    }

最佳答案

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

关于c# - 如何使用 foreach 终止和重新启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58690267/

相关文章:

PHP foreach 不循环

vba - 迭代集合 (VBA)

list - 使用 JSTL 迭代 List 和 Map 的元素 <c :forEach> tag

r - 在 foreach R 中使用列表

c# - 在 C# 中创建一个额外的桌面

c# - session变量问题c#

c# - 数据库地理类型 MakeValid 似乎不起作用

c# - 修复数据表以列出转换代码

php - 按年按月的结果 php array foreach

c# - 如何根据条件设置必填字段?