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

て烟熏妆下的殇ゞ 提交于 2019-12-24 12:39:10

问题


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

回答1:


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



回答2:


    /// <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:


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.



来源:https://stackoverflow.com/questions/21547678/making-a-thread-wait-two-seconds-before-continuing-in-c-sharp-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!