C# windows form 在控件事件触发回圈 为何不会更新UI

一般在写 windows form 程序时
如果不是大型开发
老板只要求 东西能动 项目立刻好
我们可能就会把 逻辑写在控件事件内 像是

button1_Click(object sender, EventArgs e)

如果控件事件内塞了回圈 回圈内的又希望能更新UI显示的内容 如下写法会失败

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Control_Refresh_1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 11; i++)
            {
                Thread.Sleep(200);
                textBox1.Text = i.ToString();
            }
        }
    }
}

上面的例子 回圈完全跑完才会显示10 中间的数字完全没出现
https://ithelp.ithome.com.tw/upload/images/20210302/20129372IUAdmQ5nym.png

如果希望回圈在跑的过程 就更新UI 就需要使用

Control.Refresh 方法

强制控制项使其工作区失效,并且立即重绘其本身和任何子控制项。

实际使用就是在对的地方加上

this.Refresh();

完整程序码如下

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Control_Refresh_1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 11; i++)
            {
                Thread.Sleep(200);
                textBox1.Text = i.ToString();
                this.Refresh();
            }
        }
    }
}

参考文章

https://www.ez2o.com/Blog/Post/csharp-Object-Refresh
https://www.cnblogs.com/aooyu/archive/2012/04/12/2444395.html


<<:  SQL Server 死结 (deadlock) 的分析查询 - 心得分享

>>:  【系统程序】1-3简化指令电脑(SIC)

[day28] 更新购物车内品项

昨天有改了Products表格,先换一下 -- Table: public.products -- ...

DAY 27 如何使用PyImgur

获得已上传图片资讯 修改自官网范例 import pyimgur CLIENT_ID = "...

Day_20 DNS/DDNS/Port Forwards (一)

先前介绍的几个网路架构,多数提到的IP都是在区域网路之内设备上的部份,但如果连上外网,这些资讯封包就...

【Day28】Git 版本控制 - GitBook 简介

今天来介绍一个酷东西:GitBook 图片取自 GitBook 官网 GitBook GitBook...

Day28 JQuery应用

JQuery的应用有非常多种,概念就是当触发条件达成时,我要做些甚麽,例如:滑鼠单击一下,隐藏的选单...