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

编程入门 行业动态 更新时间:2024-10-27 20:34:07
本文介绍了在 C# WPF 中继续之前让线程等待两秒钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我无法让线程在不阻塞 GUI 的情况下等待两秒钟.我知道的最简单的等待方法是Thread.Sleep(2000);.如果您可以使用一些我不知道的计时器示例或其他示例,请使用,因为我不太熟悉编码方式.

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

推荐答案

如果您使用的是 C# 5,最简单的方法是使方法 async:

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

这篇关于在 C# WPF 中继续之前让线程等待两秒钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-26 22:08:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1142853.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   WPF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!