c# - 使线程等待两秒钟,然后再继续使用C#WPF

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

最佳答案

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

关于c# - 使线程等待两秒钟,然后再继续使用C#WPF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21547678/

相关文章:

c# - 如何让 CopyFileEx 返返回告以便取消文件复制操作?

c# - 基本容器化 ASP.NET 3.1 Core 应用程序部署到 Azure ACI 失败

c# - 在 Windows 启动时启动窗口

java - 对象池通知不起作用

java - 如何等到数据接收并完全处理后,再发送下一组数据请求?

c# - 如何使用 Youtube API 检查视频观看是否受到限制?

c# - 如何在 C# 中不使用 sort 方法对数组进行排序

c# - 缩放 WPF 窗口

C# 如何确保一个异步方法在另一个异步方法之后执行

java - 无法创建自己的方法来使用selenium的显式等待方法