I'm having trouble making a thread wait for two seconds without blocking the GUI. The most simple wait method I know is Thread.Sleep(2000);
. If you can use some examples of timers or others that I'm not aware of, please do because I'm not too familiar with the ways of coding.
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();
}
}
If you're using C# 5, the simplest approach is to make the method 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();
}
See more on this question at Stackoverflow