gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:29:31 25 4
gpt4 key购买 nike

这里是我的代码,但是在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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com