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.
让线程在不阻塞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();
}
}
3 个解决方案
#1
6
If you're using C# 5, the simplest approach is to make the method async
:
如果您正在使用c# 5,最简单的方法是使方法异步:
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();
}
#2
1
/// <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);
}
#3
1
I found this approach simpler,
我发现这个方法更简单,
var task = Task.Factory.StartNew(() => Thread.Sleep(new TimeSpan(0,0,2)));
Task.WaitAll(new[] { task });
Late answer, but i hope it should be useful for someone.
答案很晚,但我希望它对某人有用。
#1
6
If you're using C# 5, the simplest approach is to make the method async
:
如果您正在使用c# 5,最简单的方法是使方法异步:
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();
}
#2
1
/// <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);
}
#3
1
I found this approach simpler,
我发现这个方法更简单,
var task = Task.Factory.StartNew(() => Thread.Sleep(new TimeSpan(0,0,2)));
Task.WaitAll(new[] { task });
Late answer, but i hope it should be useful for someone.
答案很晚,但我希望它对某人有用。