.net - 移动设备上的 OutOfMemoryException

标签 .net .net-3.5 memory windows-mobile out-of-memory

我正在开发一个应用程序,该应用程序使用移动设备拍照并使用网络服务发送照片。但是在我拍了 4 张照片之后,我在下面的代码中得到了一个 OutOfMemoryException。我尝试调用 GC.Collect() 但它也没有帮助。也许这里有人可以给我建议如何处理这个问题。

public static Bitmap TakePicture()
{
    var dialog = new CameraCaptureDialog
    {
        Resolution = new Size(1600, 1200),
        StillQuality = CameraCaptureStillQuality.Default
    };

    dialog.ShowDialog();

    // If the filename is empty the user took no picture
    if (string.IsNullOrEmpty(dialog.FileName))
       return null;

    // (!) The OutOfMemoryException is thrown here (!)
    var bitmap = new Bitmap(dialog.FileName);

    File.Delete(dialog.FileName);

    return bitmap;
}

该函数由事件处理程序调用:

private void _pictureBox_Click(object sender, EventArgs e)
{
    _takePictureLinkLabel.Visible = false;

    var image = Camera.TakePicture();
    if (image == null)
       return;

    image = Camera.CutBitmap(image, 2.5);
    _pictureBox.Image = image;

    _image = Camera.ImageToByteArray(image);
}

最佳答案

我怀疑您保留了引用资料。作为一个次要原因,请注意在使用 ShowDialog 时对话框不会自行处置,因此您应该使用 对话框(尽管我希望 GC 仍会收集未处置但未引用的对话框)。

同样,您可能应该使用 图像,但同样:不确定我是否希望它成败;不过值得一试...

public static Bitmap TakePicture()
{
    string filename;
    using(var dialog = new CameraCaptureDialog
    {
        Resolution = new Size(1600, 1200),
        StillQuality = CameraCaptureStillQuality.Default
    }) {

        dialog.ShowDialog();
        filename = dialog.FileName;
    }    
    // If the filename is empty the user took no picture
    if (string.IsNullOrEmpty(filename))
       return null;

    // (!) The OutOfMemoryException is thrown here (!)
    var bitmap = new Bitmap(filename);

    File.Delete(filename);

    return bitmap;
}

private void _pictureBox_Click(object sender, EventArgs e)
{
    _takePictureLinkLabel.Visible = false;

    using(var image = Camera.TakePicture()) {
        if (image == null)
           return;

        image = Camera.CutBitmap(image, 2.5);
        _pictureBox.Image = image;

        _image = Camera.ImageToByteArray(image);
    }
}

我也会对 CutBitmap 等保持谨慎,以确保尽快发布内容。

关于.net - 移动设备上的 OutOfMemoryException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/593951/

相关文章:

.net-3.5 - 可以将多个 XSD 文件合二为一的工具?

java - 如何使用 JVMTI 获取 java 对象的内存地址(不是哈希码)

c - C 中的 Instruments 未检测到内存泄漏

.net - 为什么可以使用反射从签名程序集中加载未签名程序集中的类型?

c# - 等待文件关闭的好方法

.net - 如何使用DPAPI加密SecureString以保存到磁盘,而无需先转换为不安全的字符串?

c++ - 对象的函数存储在内存中的什么位置?

c# - 相同的 (?) C# 和 VB.NET LINQ 查询返回不同的结果

C# 从另一个线程调用 form.show()

c# - 使用正则表达式匹配包含数字字母和破折号的字符串