下面是我的代码,但是在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;
}发布于 2019-11-04 17:35:32
在您的代码中,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();
}发布于 2019-11-04 17:28:10
代码中的问题是无法将stop重置为false。
将stop = false;从循环中删除(在循环中它什么也不做),并将它放在button1_Click中循环之外的任何位置。
https://stackoverflow.com/questions/58690267
复制相似问题