do
{
g.FillRectangle(b2, rect1);//Fill the photo b2 to rect1
Thread.Sleep(200);//delay 0.2s
g.FillRectangle(b3, rect1);
Thread.Sleep(200);
} while (true);
这个循环运行10多秒后,整个程序都崩溃了,哪个高手知道为什么啊?是不是线程睡太多了,占太多资源啊???Thread.Sleep,无限循环会不会有错啊?
{
g.FillRectangle(b2, rect1);//Fill the photo b2 to rect1
Thread.Sleep(200);//delay 0.2s
g.FillRectangle(b3, rect1);
Thread.Sleep(200);
} while (true);
这个循环运行10多秒后,整个程序都崩溃了,哪个高手知道为什么啊?是不是线程睡太多了,占太多资源啊???Thread.Sleep,无限循环会不会有错啊?
protected override void OnPaintBackground(PaintEventArgs e)
{
int i; // define value
Graphics g = this.CreateGraphics();
Rectangle rect = new Rectangle(0, 0, 0, 0); //define a figure rect1
Rectangle rect1 = new Rectangle(0, 0, 0, 0);
TextureBrush b2 = new TextureBrush(Image.FromFile(@"C:\Documents and Settings\haiquan.liang\桌面\h.jpg"));
TextureBrush b3 = new TextureBrush(Image.FromFile(@"C:\Documents and Settings\haiquan.liang\桌面\bai.jpg"));
rect1.Location = new Point(10, 40);// Change the figure rect1's starting point coordinates
rect1.Width = 200;//Set rect1's width
rect1.Height = 200;//set rect1's height
rect.Location = new Point(0, 0);// Change the figure rect1's starting point coordinates
rect.Width = 20000;// Set rect1's width
rect.Height = 20000;
g.FillRectangle(b2, rect);
i = 0;
do
{
g.FillRectangle(b2, rect1);//Fill the photo b2 to rect1
Thread.Sleep(200);//delay 0.1s
g.FillRectangle(b3, rect1);
Thread.Sleep(200);
i++;
} while (i < 20);
}
{
g.Clear();
g.FillRectangle(b2, rect1);//Fill the photo b2 to rect1
Thread.Sleep(200);//delay 0.1s
g.FillRectangle(b3, rect1);
Thread.Sleep(200);
i++;
}
正确的方法应该是在定时调用Form.Invalidate方法,然后在Paint事件里绘制,每次只绘制一张图,b2或b3,因为它们的区域都是一样的,至于要绘制的是b2还是b3,可以由你自己编写一个算法来决定。
这种方法可能会使窗体闪烁,这种情况可以设置DoubleBuffer开启双缓冲来缓解闪烁的问题。
1. 不要在主UI线程做循环
2. 最好不要在Paint时间中做循环,可能会引起多重响应事件,即使一个事件不是死循环,但互相牵诱发Paint,最终可能还是死循环。
所以这种东西,我觉得最好这样:首先将能缓存的东西先缓存,然后利用另外一个线程去死循环创建Bitmap,然后不停地更新主窗体的PictureBox,其次是注意一些资源的释放,如Bitmap和Graphics。这样可以避开比较危险地直接Paint事件。
{
public Form1()
{
InitializeComponent();
}
void Work(object obj)
{
do
{
Fill(1);
Fill(2);
} while (true);
}
void Fill(int mode)
{
if (pictureBox1.Image != null)
pictureBox1.Image.Dispose(); Bitmap img = new Bitmap(50, 50);
Rectangle rect1 = new Rectangle(0, 0, 50, 50);
Color col = mode == 1 ? Color.Red : Color.Green;
using (Graphics g = Graphics.FromImage(img))
{
g.FillRectangle(new SolidBrush(col), rect1);//Fill the photo b2 to rect1
pictureBox1.Image = img; Thread.Sleep(100);
}
} private void Form1_Load(object sender, EventArgs e)
{
ThreadPool.QueueUserWorkItem(Work);
}
}