2010-12-17 11 views
5

He creado una aplicación de prueba poco WPF que hace algunos rectángulos al azar cada 30 mseg usando System.Drawing.Graphics y de WPF InteropBitmap. Pensé que InteropBitmap sería más rápido que WriteableBitmap: tiene la capacidad de actualizarse desde la sección de memoria.de Wpf InteropBitmap junto con GDI +: uso intensivo de la CPU

Al ejecutar la aplicación (tamaño de pantalla 1600 * 1200), el uso de la CPU de la aplicación es solo de 2-10% con un doble núcleo 3GHz. Pero el uso general de la CPU es aproximadamente 80-90%, porque el proceso "Sistema (NT Kernel & Sistema") aumenta hasta un 70%. EDITAR: Y noté que el uso de RAM aumenta periódicamente en más de 1 GB en 15 segundos y de repente vuelve a su nivel normal, y así sucesivamente.

¿Quizás el siguiente código se puede optimizar? :

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> 
+0

¿Cómo se ve el proceso del sistema cuando no está ejecutando su aplicación? ¿O cuando tu aplicación llega a un punto de interrupción? Mi primer pensamiento es que el proceso es algún tipo de malware. –

+0

Entonces no consume ninguna CPU. Pero otra cosa que noté es que el uso de RAM periódicamente aumenta a 3 GB en 15 segundos y luego cae a su nivel normal, y así sucesivamente. Por lo tanto, parece que el uso de alta CPU resulta de la asignación de memoria cada 30 mseg (el evento del temporizador donde se llama interopbitmap.Invalidate()). – fritz

Respuesta

Cuestiones relacionadas