gpt4 book ai didi

c# - Thread.Sleep() 暂时挂起程序的替代方案

转载 作者:太空宇宙 更新时间:2023-11-03 17:17:01 28 4
gpt4 key购买 nike

查看本文底部的代码。它应该将“3”添加到列表框,然后在一秒钟后添加“2”,然后在一秒钟后添加“1”,然后运行程序的主要代码。但是,一旦我执行该程序,它就会保持空白 3 秒,然后显示所有 3、2 和 1,之后所有代码直接开始。我想直观地看到每个数字都有一秒钟的延迟。我该怎么做?

private void Main()
{
countdown();
//Main Code
}

private void countdown()
{
listBox1.Items.Clear();
listBox1.Items.Add("3");
System.Threading.Thread.Sleep(1000);
listBox1.Items.Add("2");
System.Threading.Thread.Sleep(1000);
listBox1.Items.Add("1");
System.Threading.Thread.Sleep(1000);
listBox1.Items.Clear();
}

最佳答案

async/await 来拯救:

private async void OnButtonClick(object sender, EventArgs e)
{
listBox1.Items.Clear();
listBox1.Items.Add("3");
await Task.Delay(1000);

listBox1.Items.Add("2");
await Task.Delay(1000);

listBox1.Items.Add("1");
await Task.Delay(1000);

listBox1.Items.Clear();
}

关于c# - Thread.Sleep() 暂时挂起程序的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32608476/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com