Delicious Cake
Delicious Cake

Reputation: 111

Making a thread wait two seconds before continuing in C# WPF

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();
     }
}

Upvotes: 1

Views: 5672

Answers (3)

Mohan Kumar
Mohan Kumar

Reputation: 6056

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.

Upvotes: 0

Vojtěch Dohnal
Vojtěch Dohnal

Reputation: 8104

    /// <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);
    }

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503180

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();
}

Upvotes: 6

Related Questions