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