我在使线程等待两秒钟而不阻塞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();
}
我是一名优秀的程序员,十分优秀!