【发布时间】:2021-09-14 04:17:48
【问题描述】:
当我点击btnStart 时,循环开始,值被添加到listBox1。我想在单击btnPause 时暂停执行,并在单击btnStart 时再次继续。我如何实现这一目标?请帮我。下面的代码我试过但没有运气。
CancellationTokenSource source = new CancellationTokenSource();
private void btnStart_Click(object sender, EventArgs e)
{
//here I want to start/continue the execution
StartLoop();
}
private async void StartLoop()
{
for(int i = 0; i < 999999; i++)
{
await Task.Delay(1000, source.Token);
listBox1.Items.Add("Current value of i = " + i);
listBox1.Refresh();
}
}
private void btnPause_Click(object sender, EventArgs e)
{
//here I want to pause/stop the execution
source.Cancel();
}
【问题讨论】:
-
你有什么问题?
-
抛出异常什么异常?
标签: c# multithreading task