完全释放byte []

时间:2017-08-03 10:36:57

标签: c# .net garbage-collection

我正在使用此代码创建一个从服务器连续性中获取字节的流应用程序:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="full-screen full-screen-1"></div>
<div class="full-screen full-screen-2"></div>
<div class="full-screen full-screen-3"></div>
<div class="full-screen full-screen-4"></div>
<div class="full-screen full-screen-5"></div>

所以我的问题是:清除byte []采取的所有内存是否足够? 我的下一个任务是将图像显示到UI。那么也许它会使内存泄漏?

更新 谢谢你们的支持。我只是意识到当我将缓冲区转换为图像并将其显示到UI而不是处理它时,我的内存泄漏问题就出现了。由于字节[]

,它没有

更新2:我更新了我的代码。请帮我查一下内存泄漏的位置?

1 个答案:

答案 0 :(得分:3)

实际上我认为将buffer设置为null是没有意义的 一旦你的循环重置,他的缓冲区将被重新定义,旧的内存将被自动GarbageCollector清除。

如果您确实发现内存泄漏,可以尝试强制进行垃圾回收,但在这种情况下,这不是必需的。 (虽然它可能取决于// Do some stuff之后您的方法如何继续。)

参考文献:

Whats so wrong about GC.Collect()?
When is it acceptable to call GC.Collect?

修改

我认为将SoftwareBitmap放在using子句中以保证资源被释放,应该可以解决内存泄漏问题。

using (SoftwareBitmap softwareBitmap = SoftwareBitmap.CreateCopyFromBuffer(buffer.AsBuffer(), BitmapPixelFormat.Gray8, 1280, 960);)
{
    buffer = null;
    GC.Collect();
    if (softwareBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 ||
        softwareBitmap.BitmapAlphaMode == BitmapAlphaMode.Straight)
    {
        softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
    }
    _imageSource = new SoftwareBitmapSource();
    await _imageSource.SetBitmapAsync(softwareBitmap);

    // Set the source of the Image control
    image_Preview.Source = _imageSource;
}