我无法做一个线程等待两秒钟,而不会阻塞GUI。 最简单的wait方法,我知道是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();
}
/// <summary>
/// WPF Wait
/// </summary>
/// <param name="seconds"></param>
public static void Wait(double seconds)
{
var frame = new DispatcherFrame();
new Thread((ThreadStart)(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(seconds));
frame.Continue = false;
})).Start();
Dispatcher.PushFrame(frame);
}
我发现这种方法比较简单,
var task = Task.Factory.StartNew(() => Thread.Sleep(new TimeSpan(0,0,2)));
Task.WaitAll(new[] { task });
迟到的回答,但我希望它应该是有用的人。