c# - 线程没有真正休眠?

标签 c# wpf thread-sleep

我试图在用户单击 Enter 后将 TextBox 禁用几秒钟:

<StackPanel>
    <TextBox x:Name="txt1" Width="150" Margin="10" KeyUp="txt1_KeyUp"/>
</StackPanel>   

private void txt1_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            txt1.IsEnabled = false;
            Thread.Sleep(2500);
            txt1.IsEnabled = true; //all text is added here
        }
    }

如果我在 Thread 休眠时继续键入,当 Thread “唤醒”时,我键入的所有内容都会在 TextBox 中弹出。

我的问题是,当 GUI 线程休眠时,是否有某种缓冲区可以存储所有引发的事件?

最佳答案

这里有一个更好的解决方案:

<StackPanel>
    <TextBox x:Name="txt1" Width="150" Margin="10" KeyUp="txt1_KeyUp"/>
</StackPanel>   

private void txt1_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        txt1.IsEnabled = false;
        Thread t = new Thread(() =>
        {
            System.Threading.Thread.Sleep(2500);
            Action action = () => txt1.IsEnabled = true;
            Dispatcher.Invoke(action);
        });
        t.Start();
    }
}

您会看到,当您按下回车键时,该框被禁用,您不会在 UI 线程上休眠。

如果您希望其他 UI 元素知道此操作何时完成,您可以将 t(线程)保存到表单中,您可以查询它的状态 (t.ThreadState) 以确定它是否已完成。

关于c# - 线程没有真正休眠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16581756/

相关文章:

multithreading - 所有goroutines死锁

c# - Thread.Sleep 的精度还很差吗?

c# - WPF、C# 中组合框的 DisplayMemberPath

c# - Web 应用程序中的 Newtonsoft.Json 6.0.0.0 和 12.0.0.0 与 Web Api、C# 发生冲突

c# - 如何在 asp.net core web api 中绑定(bind) Json 查询字符串

c# - 将List<>写入数据库asp.net

wpf - 仅将 WPF 样式应用于一个按钮

c# - 将 DataContext 级联到集合中的子元素的自定义控件

java - 暂停线程的最佳方法?

C#访问类内部静态