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就好比實現了進程的同步。在不加的時候,因為優先級的問題,程序會執行主進程的代碼,再執行別代碼,而加了以后就可以同步執行
2、使用線程等待,即Thread.Sleep(5000);
3、使用winForm的invalidate(),設置區域重繪