c# MemoryStream减慢程序性能

本文关键字:程序性 性能 程序 MemoryStream | 更新日期: 2023-09-27 18:18:24

我正在做一个使用WPF显示Kinect ColorImageFrame和骨架表示的项目。我还得录那两个视频。

我能够显示和记录(使用EmguCV)这两个图像,但我有一些性能问题。看来这部分代码是我性能下降的原因。

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;       
        }            
    }

,更准确地说,是从ToWpfBitmap,它允许我在我的窗口中显示它:

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;
        }
    }

性能损失表现为:—窗口显示的视频不再流畅-视频录制似乎漏掉了一些帧,导致视频比正常速度更快/更慢。

你能告诉我这个问题可能来自哪里吗?

c# MemoryStream减慢程序性能

尝试使用recyablememorystream代替MemoryStream。它是为解决内存问题而设计的。

查看这篇文章了解详情-宣布Microsoft.IO.RecycableMemoryStream

您是否尝试过在单独的线程中进行内存写i/o,同时将数据保存在缓冲区中,如队列?