从表单中取消并行循环
Cancel Parallel loop from form
我有一个带有文本框的 C# 表单。
我想要 运行 一个事件,这样每次在文本框中更改文本时它都会取消最后一个 parallel.for 循环并使用新信息重新启动,但是我不知道如何当此事件为 运行.
时,检索旧的取消令牌以取消上一次迭代
我希望下面的代码能解释我想做什么
private void Textbox_TextChanged(object sender, EventArgs e)
{
//call previous cancellation token from Textbox.tag and execute
CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions op = new ParallelOptions();
op.CancellationToken = cts.Token;
Parallel.For(0, 1, op, t =>
{
//Store cancellation token in textbox.tag
//do stuff
});
}
提前致谢
您需要 declare/store 它在方法范围之外:
private CancellationTokenSource cts = new CancellationTokenSource();
private ParallelOptions op = new ParallelOptions();
private void Textbox_TextChanged(object sender, EventArgs e)
{
//call previous cancellation token from Textbox.tag and execute
cts.Cancel();
cts = new CancellationTokenSource();
op = new ParallelOptions();
op.CancellationToken = cts.Token;
Parallel.For(0, 1, op, t =>
{
//do stuff
});
}
我有一个带有文本框的 C# 表单。
我想要 运行 一个事件,这样每次在文本框中更改文本时它都会取消最后一个 parallel.for 循环并使用新信息重新启动,但是我不知道如何当此事件为 运行.
时,检索旧的取消令牌以取消上一次迭代我希望下面的代码能解释我想做什么
private void Textbox_TextChanged(object sender, EventArgs e)
{
//call previous cancellation token from Textbox.tag and execute
CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions op = new ParallelOptions();
op.CancellationToken = cts.Token;
Parallel.For(0, 1, op, t =>
{
//Store cancellation token in textbox.tag
//do stuff
});
}
提前致谢
您需要 declare/store 它在方法范围之外:
private CancellationTokenSource cts = new CancellationTokenSource();
private ParallelOptions op = new ParallelOptions();
private void Textbox_TextChanged(object sender, EventArgs e)
{
//call previous cancellation token from Textbox.tag and execute
cts.Cancel();
cts = new CancellationTokenSource();
op = new ParallelOptions();
op.CancellationToken = cts.Token;
Parallel.For(0, 1, op, t =>
{
//do stuff
});
}