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

在执行应用程序(屏幕尺寸1600 * 1200)时,应用程序的CPU使用率仅为 2-10%(双核3GHz)。但是总体CPU使用率约为 80-90%,因为“系统(NT内核和系统)”进程最多上升了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>

最佳答案

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();”之后称呼。

关于c# - WPF的InteropBitmap与GDI + : high cpu usage,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4473515/

10-11 01:54