This project is read-only.

Improvement on BitmapConversion.cs

Aug 21, 2014 at 8:28 AM
Edited Aug 21, 2014 at 8:31 AM
Hi,

while making first steps with SharpGL I found that calling the garbage collection in the BitmapConversion takes up the most time while rendering.

So I tweaked that part in the code a bit to be non blocking.
    /// <summary>
    /// This class handles conversion to and from various bitmap types.
    /// </summary>
    public static class BitmapConversion
    {
        // Contains the current Thread that calls the GC.
        private static Thread runGCThread =null;

        /// <summary>
        /// Converts an HBitmap the bitmap to a bitmap source.
        /// </summary>
        /// <param name="hBitmap">The hbitmap.</param>
        /// <returns>A BitmapSource.</returns>
        public static BitmapSource HBitmapToBitmapSource(IntPtr hBitmap)
        {
             ...
            finally
            {
                // Always clean hBitmap
                Win32.DeleteObject(hBitmap);

                // Only start a new Thread when previous has finished.
                if (BitmapConversion.runGCThread == null)
                {
                    BitmapConversion.runGCThread = new Thread(RunGC);
                    BitmapConversion.runGCThread.Start();
                }
            }

            return bitSrc;
        }

        /// <summary>
        /// Performs a call to the GC.
        /// </summary>
        private static void RunGC()
        {
            try
            {
                GC.Collect();
            }
            finally
            {
                BitmapConversion.runGCThread = null;
            }
        }
...
A further improvement might be to not call the GC when enough free memory remains, or only do it once a second.

Hope this helps a bit in improving the performance.

Edit: If you've not recognized, I'm working with the WPF part ;-)

By the way: Thank you for all the work that was spend into this project.

Cheers

Thomas
Sep 7, 2014 at 5:50 PM
Thanks for bringing this to my attention, I'll look over the improvements when I profile SharpGL for the next release and incorporate them then!
Jan 13, 2015 at 12:20 PM
Hi,

The call to the garbage collection should be done with blocking=true. Otherwise there might be multiple calls to the collect method.
try
{
            GC.Collect(2, GCCollectionMode.Forced, true);
            System.Threading.Thread.Sleep(1000);
}
finally
{
            BitmapConversion.runGCThread = null;
}
I've also added a small timeout to reduce heavy CPU load.