在继续使用C#WPF之前,让线程等待两秒钟

时间:2014-02-04 08:47:28

标签: c# wpf wait

我无法在不阻止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 个答案:

答案 0 :(得分:6)

如果您使用的是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();
}

答案 1 :(得分: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);
    }

答案 2 :(得分:1)

我发现这种方法更简单,

var task = Task.Factory.StartNew(() => Thread.Sleep(new TimeSpan(0,0,2)));
Task.WaitAll(new[] { task });

迟到的答案,但我希望它对某人有用。