Wpf的InteropBitmap和GDI +:高CPU使用率

时间:2010-12-17 18:11:58

标签: c# wpf interop gdi+

我已经创建了一个小的wpf测试应用程序,它使用 System.Drawing.Graphics 和wpf的 InteropBitmap 每30毫秒渲染一些随机矩形。我认为InteropBitmap比WriteableBitmap更快:它能够从内存部分更新自己。

在执行应用程序(屏幕大小1600 * 1200)时,应用程序的CPU使用率仅为 2-10%,具有双核3GHz。但是整体cpu使用率大约是 80-90%,因为“System(NT Kernel& System”)进程上升到70%! 编辑:我注意到RAM的使用在15秒内会定期增加1 GB以上,然后突然回落到正常水平,依此类推。

也许可以优化以下代码? :

namespace InteropBitmapTest{

 using System;
 using System.Drawing;
 using System.Runtime.InteropServices;
 using System.Windows;
 using System.Windows.Interop;
 using System.Windows.Media;
 using System.Windows.Media.Imaging;
 using Color = System.Drawing.Color;

public partial class Window1 : Window
{

    private System.Drawing.Bitmap gdiBitmap;
    private Graphics graphics;


    InteropBitmap interopBitmap;

    const uint FILE_MAP_ALL_ACCESS = 0xF001F;
    const uint PAGE_READWRITE = 0x04;

    private int bpp = PixelFormats.Bgr32.BitsPerPixel / 8;

    private Random random;
    private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();


    SolidBrush[] brushes = new SolidBrush[] { new SolidBrush(Color.Lime), new SolidBrush(Color.White) };


    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr CreateFileMapping(IntPtr hFile,
    IntPtr lpFileMappingAttributes,
    uint flProtect,
    uint dwMaximumSizeHigh,
    uint dwMaximumSizeLow,
    string lpName);

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr MapViewOfFile(IntPtr hFileMappingObject,
    uint dwDesiredAccess,
    uint dwFileOffsetHigh,
    uint dwFileOffsetLow,
    uint dwNumberOfBytesToMap);

    public Window1()
    {
        InitializeComponent();

        Loaded += Window1_Loaded;

        WindowState = WindowState.Maximized;

        timer.Tick += timer_Tick;
        timer.Interval = 30;

        random = new Random();

    }

    void Window1_Loaded(object sender, RoutedEventArgs e)
    {
        // create interopbitmap, gdi bitmap, get Graphics object
        CreateBitmaps();


        // start drawing 100 gdi+ rectangles every 30 msec:
        timer.Start();
    }


    void timer_Tick(object sender, EventArgs e)
    {
        int width = 50;


        // Draw 100 gdi+ rectangles :


        for (int i = 0; i < 100; i++)
        {
            int left = random.Next((int)(ActualWidth - width));
            int top = random.Next((int)(ActualHeight - width));


            graphics.FillRectangle(brushes[left % 2], left, top, width, width);

        }


        interopBitmap.Invalidate(); // should only update video memory (and not copy the whole bitmap to video memory before)

    }


    void CreateBitmaps()
    {

        uint byteCount = (uint) (ActualWidth * ActualHeight * bpp);


        //Allocate/reserve memory to write to

        var sectionPointer = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, PAGE_READWRITE, 0, byteCount, null);

        var mapPointer = MapViewOfFile(sectionPointer, FILE_MAP_ALL_ACCESS, 0, 0, byteCount);

        var format = PixelFormats.Bgr32;

        //create the InteropBitmap

        interopBitmap = Imaging.CreateBitmapSourceFromMemorySection(sectionPointer, (int)ActualWidth, (int)ActualHeight, format,
            (int)(ActualWidth * format.BitsPerPixel / 8), 0) as InteropBitmap;


        //create the GDI Bitmap

        gdiBitmap = new System.Drawing.Bitmap((int)ActualWidth, (int)ActualHeight,
                                    (int)ActualWidth * bpp,
                                     System.Drawing.Imaging.PixelFormat.Format32bppPArgb,
                                    mapPointer);

        // Get good old GDI Graphics

        graphics = Graphics.FromImage(gdiBitmap);


        // set the interopbitmap as Source to the wpf image defined in XAML 

        wpfImage.Source = (BitmapSource) interopBitmap; 

    }





}}

XAML:

<Window x:Class="InteropBitmapTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
  <Image Name="wpfImage" Stretch="None" />
</Window>

1 个答案:

答案 0 :(得分:5)

WTF:这是一个 InteropBitmap内存泄漏,它在.NET 4.0中是新功能:

http://connect.microsoft.com/VisualStudio/feedback/details/603004/massive-gpu-memory-leak-with-interopbitmap

https://connect.microsoft.com/VisualStudio/feedback/details/585875/interopbitmap-is-way-less-performant-in-net-4-0-vs-net-3-5

将目标框架设置为3.5,一切正常!

另一种选择是放“GC.Collect();”在每个“interopBitmap.Invalidate();”之后调用