首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用foreach终止和重新启动

如何使用foreach终止和重新启动
EN

Stack Overflow用户
提问于 2019-11-04 17:17:16
回答 2查看 75关注 0票数 1

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

代码语言:javascript
运行
复制
    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;
    }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-11-04 17:35:32

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

代码语言:javascript
运行
复制
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();
}
票数 2
EN

Stack Overflow用户

发布于 2019-11-04 17:28:10

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

stop = false;从循环中删除(在循环中它什么也不做),并将它放在button1_Click中循环之外的任何位置。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58690267

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档