简体   繁体   English

C# For loop 几秒后恒速立即完成

[英]C# For loop after few seconds constant speed immediately complete

I have this codo for draw rectangles into ImageBox one by one.我有这个 codo 用于将矩形一个一个地绘制到 ImageBox 中。

        g = Graphics.FromImage(pictureBox1.Image);
        int size = 40;
        int squares = 0;

        for (int H = 0; H < 1490; H += size)
        {
            for (int W = 0; W < 1490; W += size)
            {
                var rectangle = new Rectangle(W, H, size, size);
                g.DrawRectangle(new Pen(Color.Green, 3), rectangle);
                this.Refresh();
                squares++;
                label1.Text = squares.ToString();
            }
        }

In Visual Studio everything works as it should do, but when I build it works for first 300 ~ rectangles and then lag and instantly complete.在 Visual Studio 中,一切正常,但当我构建它时,它适用于前 300 个 ~ 矩形,然后滞后并立即完成。

I figure that Refresh() stop working.我认为 Refresh() 停止工作。

Using Refresh();使用刷新(); is slow and not effective.很慢而且没有效果。 Rather use something pictureBox1.Image = pictureBox1.Image;.而是使用一些pictureBox1.Image = pictureBox1.Image;。 I used StopWatch with while loop to wait few ms for slowing loop and setting fixed interval even if loop takes more time that others.我使用 StopWatch 和 while 循环来等待几毫秒以减慢循环并设置固定间隔,即使循环比其他循环花费更多时间。

Thanks @jdweng (good point) and @TaW (lots of good informations).感谢@jdweng(好点)和@TaW(很多好信息)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM