gpt4 book ai didi

c# - 使线程等待两秒钟,然后再继续使用C#WPF

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

我在使线程等待两秒钟而不阻塞GUI时遇到麻烦。我知道的最简单的等待方法是Thread.Sleep(2000);。如果您可以使用一些计时器示例或我不知道的其他示例,请执行此操作,因为我对编码方式不太熟悉。

private void run_program_Click(object sender, RoutedEventArgs e)
{
if (comboBox1.Text == "Drive forwards and back")
{
stop.IsEnabled = true;

EngineA(90); //Makes EngineA drive at 90% power
EngineB(90); //Makes EngineB drive at 90% power

// Basicly it has to wait two seconds here

EngineA(-90); // -90% power aka. reverse
EngineB(-90); // -90% power

// Also two seconds here

EngineA(0); // Stops the engine
EngineB(0); // Stops
EngineC();
}
}

最佳答案

如果您使用的是C#5,则最简单的方法是使方法async

private async void RunProgramClick(object sender, RoutedEventArgs e)
{
// Reverse the logic to reduce nesting and use "early out"
if (comboBox1.Text != "Drive forwards and back")
{
return;
}

stop.IsEnabled = true;
EngineA(90);
EngineB(90);

await Task.Delay(2000);

EngineA(-90);
EngineB(-90);

await Task.Delay(2000);

EngineA(0);
EngineB(0);
EngineC();
}

关于c# - 使线程等待两秒钟,然后再继续使用C#WPF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21547678/

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