天天看点

C#子线程中更新主线程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.Tasks;
using System.Windows.Forms;namespace WindowsFormsAppTestDoEvent
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 10000; i++)
            {
                label1.Text = i.ToString();
                Application.DoEvents();
                //测试了一下,没有Application.DoEvents()的时候,Label基本处于假死机状态,最后显示一个9999,
                //加上后会数字变换正常显示。
                //从这个测验后DoEvents的功能,应该DoEvents就好比实现了进程的同步。在不加的时候,因为优先级的问题,程序会执行主进程的代码,再执行别代码,而加了以后就可以同步执行
            }
        }
    }
}      

主线程UI更新不及时或者多线程时更新不正确,可以使用一下方式解决

1、Application.DoEvents();

测试了一下,没有Application.DoEvents()的时候,Label基本处于假死机状态,最后显示一个9999,

//加上后会数字变换正常显示。

//从这个测验后DoEvents的功能,应该DoEvents就好比实现了进程的同步。在不加的时候,因为优先级的问题,程序会执行主进程的代码,再执行别代码,而加了以后就可以同步执行

继续阅读