【问题标题】:C# CopyFromScreen filling up memoryC# CopyFromScreen 填满内存
【发布时间】:2014-02-10 22:52:03
【问题描述】:

我正在使用此代码通过计时器每秒拍摄一次屏幕截图,但它似乎正在填满我的内存(每次拍摄大约 30 MB)...这是代码:

Bitmap bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
Graphics gfxScreenshot = Graphics.FromImage(bmpScreenshot);
gfxScreenshot.CopyFromScreen(136, 93, 9, 0, new Size(1088-391, 1039-65), CopyPixelOperation.SourceCopy);

return bmpScreenshot;

有没有办法清除内存?

【问题讨论】:

  • 你需要Dispose()的东西。

标签: c# .net memory screenshot


【解决方案1】:

您需要通过调用Dispose 或包装为您调用它的using() 语句来正确处理东西,例如:

Bitmap bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);

using(Graphics gfxScreenshot = Graphics.FromImage(bmpScreenshot)) {
    gfxScreenshot.CopyFromScreen(136, 93, 9, 0, new Size(1088-391, 1039-65),   CopyPixelOperation.SourceCopy);
}

return bmpScreenshot;

您还应该在完成后处理返回的 Bitmap 实例。

【讨论】:

  • @user1176999 你能详细说明一下吗?你得到什么错误?
【解决方案2】:

我也遇到过这个问题。

var g = CreateGraphics();

using (var brush = new SolidBrush(Color.Red))
{
    Point point = new Point(0,0);
    Rectangle sourceRect = new Rectangle(100,100,100,100);

    var invoker = new MethodInvoker(() =>
    {
        // The following line will filling up the memory.
        g.CopyFromScreen(new Point(0,0), sourceRect.Location, sourceRect.Size);
    });
    do
    {
        BeginInvoke(invoker);
    } while (!mre.WaitOne(1));
}

这意味着“CopyFromScreen”方法有一些未处理的东西。 但我不知道如何处置它们。 即使通过 VS2017 的“诊断工具”,我也可以看到堆使用情况并指向 ExecutionContext -> Queue,Queue 越来越大,并且大多数情况下,Queue 中每个项目的大小为 44 字节。当然,GC会在一段时间后收集它们,但它仍然会快速增长。

【讨论】:

    【解决方案3】:

    BitmapGraphics 实现 IDisposable 接口。要释放非托管资源,您应该调用 Dispose 方法或使用 using 语句包装两个对象。

    【讨论】:

    • 抱歉,它似乎按照文档执行,但是,当我在位图周围添加 using() 时,它抛出了一个错误,说它没有实现 IDisposable 所以现在我很困惑.. .我删除了我之前的评论
    猜你喜欢
    • 2018-03-06
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    相关资源
    最近更新 更多