Florent Gz
Florent Gz

Reputation: 934

C# MemoryStream slowing programme performance

I'm working on a project using WPF to display the Kinect ColorImageFrame and a skeleton representation. I also have to record those two videos.

I'm able to display and record (using EmguCV) those two images, but I have some performance issues. It seems that this part of my code is the reason of my loss of performance.

private void DrawSkeleton(Skeleton[] skeletons)
    {
        using (System.Drawing.Bitmap skelBitmap = new System.Drawing.Bitmap(640, 480))
        {
            foreach (Skeleton S in skeletons)
            {
                if (S.TrackingState == SkeletonTrackingState.Tracked)
                {
                    DrawBonesAndJoints(S,skelBitmap);                        
                }
                else if (S.TrackingState == SkeletonTrackingState.PositionOnly)
                {

                }
            }
            _videoArraySkel.Add(ToOpenCVImage<Bgr, Byte>(skelBitmap));
            BitmapSource source = ToWpfBitmap(skelBitmap);
            this.skeletonStream.Source = source;       
        }            
    }

and more precisely from the ToWpfBitmap which allows me to display it in my Window:

public static BitmapSource ToWpfBitmap(System.Drawing.Bitmap bitmap) 
    {
        using (MemoryStream stream = new MemoryStream()) 
        {
            bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
            stream.Position = 0;
            BitmapImage result = new BitmapImage();
            result.BeginInit();
            // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
            // Force the bitmap to load right now so we can dispose the stream.
            result.CacheOption = BitmapCacheOption.OnLoad;
            result.StreamSource = stream;
            result.EndInit();
            result.Freeze();
            return result;
        }
    }

The loss of performance is characterized by: - The videos displayed on the Window are not fluent anymore - The video recording seems to miss some frames which leads to a video going faster/lower than the normal.

Can you help me by telling me where this problem may come from?

Upvotes: 0

Views: 2890

Answers (2)

RredCat
RredCat

Reputation: 5421

Try to use RecyclableMemoryStream instead of MemoryStream. It was designed for solving some issue with memory.

Check out this article for details - Announcing Microsoft.IO.RecycableMemoryStream

Upvotes: 1

D.S.
D.S.

Reputation: 289

Have you tried doing the memory write i/o in a separate thread, while maintaining the data in a buffer like a queue?

Upvotes: 0

Related Questions