如何通过按钮单击退出循环 [英] How to make exit from loop by button click
本文介绍了如何通过按钮单击退出循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想点击[取消]按钮退出循环。
I want to make exit from loop by clicking [Cancel] button.
我制作了样本测试程序。
I made sample test program.
有太按钮,一个是[开始],它开始循环,另一个是[取消],它将变量设置为真,以便退出循环。
There are too buttons, one is [Start], which starts loop and another is [Cancel], which set variable to true in order to make exit from loop.
public partial class Form1 : Form
{
bool CancelClicked = false;
public Form1()
{
InitializeComponent();
}
private void CancelButton_Click(object sender, EventArgs e)
{
CancelClicked = true;
}
private void StartButton_Click(object sender, EventArgs e)
{
do
{
Application.DoEvents();
Thread.Sleep(100);
if (CancelClicked == true)
{
CancelClicked = false;
MessageBox.Show("exit loop!");
break;
}
} while (true);
}
}
但是"if(CancelClicked = = = true)"在CancelButton_Click事件中未检测到CancelClicked已更改。
However "if (CancelClicked == true)" doesn't detect CancelClicked is changed in CancelButton_Click event.
如何通过单击[取消]按钮退出循环?
How can I make exit from loop by clicking [Cancel] button?
推荐答案
尝试以下
CancellationTokenSource cTokenSource = new CancellationTokenSource();
private async void button1_Click(object sender, EventArgs e)
{
cTokenSource = new CancellationTokenSource();
int i;
for (i = 0; i < 10000; i++)
{
Console.WriteLine("Number: {0}", i);
await Task.Delay(1);
if (cTokenSource.IsCancellationRequested)
{
break;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
cTokenSource.Cancel();
}
或
CancellationTokenSource cTokenSource = new CancellationTokenSource();
private async void button1_Click(object sender, EventArgs e)
{
cTokenSource = new CancellationTokenSource();
int i = 0;
do
{
Console.WriteLine(
" {i}");
i + = 1;
await Task.Delay(1);
if(cTokenSource.IsCancellationRequested)
{
break;
}
} while(true);
}
private void button2_Click(object sender,EventArgs e)
{
cTokenSource.Cancel();
}
"{i}"); i += 1; await Task.Delay(1); if (cTokenSource.IsCancellationRequested) { break; } } while (true); } private void button2_Click(object sender, EventArgs e) { cTokenSource.Cancel(); }
这篇关于如何通过按钮单击退出循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文