在整个循环完成之前,标签文本不会更新

我有一个Winform程序,当用户点击一个按钮然后调用picturebox paint事件来根据计算结果绘制一个新的BMP时进行一些计算。 这很好用。

现在我想这样做100次,每次刷新图片框时,我希望通过更新标签上的文本来查看当前的迭代:

private void button2_Click(object sender, EventArgs e) { for (int iterations = 1; iterations <= 100; iterations++) { // do some calculations to change the cellmap parameters cellMap.Calculate(); // Refresh picturebox1 pictureBox1.Invalidate(); pictureBox1.Update(); // Update label with the current iteration number label1.Text = iterations.ToString(); } } private void pictureBox1_Paint(object sender, PaintEventArgs e) { Bitmap bmp = new Bitmap(cellMap.Dimensions.Width, cellMap.Dimensions.Height); Graphics gBmp = Graphics.FromImage(bmp); int rectWidth = scaleFactor; int rectHeight = scaleFactor; // Create solid brushes Brush blueBrush = new SolidBrush(Color.Blue); Brush greenBrush = new SolidBrush(Color.Green); Brush transparentBrush = new SolidBrush(Color.Transparent); Graphics g = e.Graphics; for (int i = 0; i < cellMap.Dimensions.Width; i++) { for (int j = 0; j < cellMap.Dimensions.Height; j++) { // retrieve the rectangle and draw it Brush whichBrush; if (cellMap.GetCell(i, j).CurrentState == CellState.State1) { whichBrush = blueBrush; } else if (cellMap.GetCell(i, j).CurrentState == CellState.State2) { whichBrush = greenBrush; } else { whichBrush = transparentBrush; } // draw rectangle to bmp gBmp.FillRectangle(whichBrush, i, j, 1f, 1f); } } g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; g.DrawImage(bmp, 0, 0, pictureBox1.Width, pictureBox1.Height); } 

我遇到的问题是标签文本仅在最后一个图片框更新完成后才会显示。 基本上,它不显示1到99.我可以看到每次刷新后的图片框更新,因为BMP随着每次迭代而变化。 任何的想法?

要回答有关为何必须执行此操作的问题:Windows窗体程序在单个线程中运行所有内容 – UI线程。 这意味着它必须按顺序执行代码,以便在它切换回UI代码之前完成一个函数。 换句话说,它在完成function之前无法更新图片,因此如果您更新图片100次,则只会更新最后一张图片。 使用Invalidate / Update代码告诉编译器“暂停”函数的执行并强制它更新UI而不是等到函数结束。 希望有所帮助!

 // Code fragement... // 5 cent solution, add Invalidate/Update label1.Text = iterations.ToString(); label1.Invalidate(); label1.Update();