【发布时间】:2010-12-16 02:47:46
【问题描述】:
我有一个后台线程,它在给定文件夹中创建图像的灰度缩略图。我看到的问题是后台线程中的 Graphics.DrawImage() 调用似乎以某种方式阻塞了主 UI 线程上的 Graphics 操作。
我可能误解了我在这里看到的内容,并且直到今晚晚些时候才有机会进行任何深入的分析,尽管我不希望能找到太多。
我试图想出一个尽可能小的复制案例。如果您将默认项目中的表单替换为下面的表单(并在文件夹中有一些图像进行测试),您会注意到动画标签在窗口中来回弹跳时会结结巴巴。但是,如果您取消注释顶部的#define 以便子控件设置动画而不是重绘窗口内容,它会非常流畅地运行。
谁能看到我在这里做错了什么或帮助我弄清楚如何在更新循环期间避免这种卡顿?
//#define USE_LABEL_CONTROL
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using Timer = System.Windows.Forms.Timer;
namespace ThreadTest
{
public partial class Form1 : Form
{
private const string ImageFolder = "c:\\pics";
private const string ImageType = "*.jpg";
public Form1()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
this.Size = new Size(300, 300);
string[] ImageFiles = Directory.GetFiles(ImageFolder,
ImageType,
SearchOption.AllDirectories);
// kick off a thread to create grayscale thumbnails of all images
this.thumbnailThread = new Thread(this.thumbnailThreadFunc);
this.thumbnailThread.Priority = ThreadPriority.Lowest;
this.thumbnailThread.Start(ImageFiles);
// set a timer to start us off...
this.startTimer = new Timer();
this.startTimer.Interval = 500;
this.startTimer.Tick += this.startTimer_Tick;
this.startTimer.Start();
#if USE_LABEL_CONTROL
this.label.Location = this.labelRect.Location;
this.label.Size = this.labelRect.Size;
this.label.Text = "Loaded: 0";
this.label.BorderStyle = BorderStyle.FixedSingle;
this.Controls.Add(this.label);
#endif
base.OnLoad(e);
}
void startTimer_Tick(object sender, EventArgs e)
{
// kill the timer
this.startTimer.Stop();
// update ourself in a loop
while (this.IsHandleCreated)
{
int NextTick = Environment.TickCount + 50;
// update the label position
this.labelRect.Offset(this.currentLabelDirection, 0);
if (this.labelRect.Right == this.ClientRectangle.Right ||
this.labelRect.Left == 0)
{
this.currentLabelDirection = -this.currentLabelDirection;
}
// update the display
#if USE_LABEL_CONTROL
this.label.Text = "Loaded: " + this.thumbs.Count;
this.label.Location = this.labelRect.Location;
#else
using (Graphics Dest = this.CreateGraphics())
{
this.redrawControl(Dest, this.ClientRectangle);
}
#endif
Application.DoEvents();
Thread.Sleep(Math.Max(0, NextTick - Environment.TickCount));
}
}
private void thumbnailThreadFunc(object ThreadData)
{
string[] ImageFiles = (string[]) ThreadData;
foreach (string ImageFile in ImageFiles)
{
if (!this.IsHandleCreated)
{
return;
}
using (Image SrcImg = Image.FromFile(ImageFile))
{
Rectangle SrcRect = new Rectangle(Point.Empty, SrcImg.Size);
Rectangle DstRect = new Rectangle(Point.Empty, new Size(300, 200));
Bitmap DstImg = new Bitmap(DstRect.Width, DstRect.Height);
using (Graphics Dst = Graphics.FromImage(DstImg))
{
using (ImageAttributes Attrib = new ImageAttributes())
{
Attrib.SetColorMatrix(this.grayScaleMatrix);
Dst.DrawImage(SrcImg,
DstRect,
0, 0, SrcRect.Width, SrcRect.Height,
GraphicsUnit.Pixel,
Attrib);
}
}
lock (this.thumbs)
{
this.thumbs.Add(DstImg);
}
}
}
}
#if !USE_LABEL_CONTROL
private void redrawControl (Graphics Dest, Rectangle UpdateRect)
{
Bitmap OffscreenImg = new Bitmap(this.ClientRectangle.Width,
this.ClientRectangle.Height);
using (Graphics Offscreen = Graphics.FromImage(OffscreenImg))
{
Offscreen.FillRectangle(Brushes.White, this.ClientRectangle);
Offscreen.DrawRectangle(Pens.Black, this.labelRect);
Offscreen.DrawString("Loaded: " + this.thumbs.Count,
SystemFonts.MenuFont,
Brushes.Black,
this.labelRect);
}
Dest.DrawImageUnscaled(OffscreenImg, 0, 0);
OffscreenImg.Dispose();
}
protected override void OnPaintBackground(PaintEventArgs e)
{
return;
}
protected override void OnPaint(PaintEventArgs e)
{
this.redrawControl(e.Graphics, e.ClipRectangle);
}
#endif
private ColorMatrix grayScaleMatrix = new ColorMatrix(new float[][]
{
new float[] {.3f, .3f, .3f, 0, 0},
new float[] {.59f, .59f, .59f, 0, 0},
new float[] {.11f, .11f, .11f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
});
private Thread thumbnailThread;
private Timer startTimer;
private List<Bitmap> thumbs = new List<Bitmap>();
private Label label = new Label();
private int currentLabelDirection = 1;
private Rectangle labelRect = new Rectangle(0, 125, 75, 20);
}
}
【问题讨论】:
-
啊,DoEvents() 的邪恶又来了。
-
即使在后台线程加载了所有图像后,图像动画是否继续卡顿?如果您要加载少量图像,我希望它们几乎可以立即加载。尝试在没有后台线程的情况下加载图像,看看是否是您的动画循环问题。计时器滴答事件处理程序中的 Application.DoEvents 和 Thread.Sleep 非常可疑。
-
所有图片加载完毕后运行流畅。我添加了 ~50ms 更新循环和 DoEvents() 调用来消除 WM_TIMER 和 WM_PAINT 优先级问题的任何可能性。注释掉后台线程中的 DrawImage() 调用也会使其顺利运行。
-
我还应该补充一点,这是一台四核 2 GHz 机器,有足够的 RAM 可用。
-
在分析器中查看此内容,我看到 GDI+ 在等待后台线程中的 DrawImage() 调用时似乎在主线程中阻塞。具体来说,FillRect() 调用在通过 GdipFillRectangle 之后阻塞,向下进入 GpGraphics::RenderFillRects,然后从那里进入 Devlock::Devlock,它试图进入临界区。显然,您不能在后台线程上无缝地执行冗长的 GDI+ 操作,同时也在 UI 线程上使用 GDI+。令人沮丧,至少可以这么说。除非有人可以提供解决方法,否则我会将其重新发布为答案。
标签: c# multithreading gdi+ blocking