使用Thread.Sleep时UI不更新 [英] UI Not Updating when Using Thread.Sleep

查看:64
本文介绍了使用Thread.Sleep时UI不更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有需要按钮的应用程序,每隔1秒钟单击此按钮一次,将特殊文本添加到TextBox中,但是当单击此按钮时,始终等待并一起输入所有文本.

I have application that have button i want when click this button every 1 second add special text add to a TextBox but when click this button all time wait and enter all text together.

出什么问题了?

例如:

 private void button2_Click(object sender, RoutedEventArgs e)
        {
            Random rand = new Random(DateTime.Now.Millisecond);
            textBox1.Text = "";
            for (int i = 0; i < 10; i++)
            {
                textBox1.Text += rand.Next(1,10) + "\n";
                System.Threading.Thread.Sleep(1000);
            }
        }

谢谢.

推荐答案

您正在UI线程上睡觉.
这样会冻结UI.

You're sleeping on the UI thread.
This freezes the UI.

相反,请使用 BackgroundWorker 及其进度事件.

Instead, use a BackgroundWorker and its progress events.

这篇关于使用Thread.Sleep时UI不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆