Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从本地存储加载图片>;OutofmemoryException-C#-Xamarin.Forms_C#_Xamarin.forms_Out Of Memory - Fatal编程技术网

从本地存储加载图片>;OutofmemoryException-C#-Xamarin.Forms

从本地存储加载图片>;OutofmemoryException-C#-Xamarin.Forms,c#,xamarin.forms,out-of-memory,C#,Xamarin.forms,Out Of Memory,当我想从内存加载图片时,有时会出现延迟,但有时会出现内存异常 var picList = System.Instance.GetFiles("/storage/emulated/0/DCIM/Camera", true); //Its a string list, include the files name var inc = 0; foreach (var item in picList)

当我想从内存加载图片时,有时会出现延迟,但有时会出现内存异常

var picList = System.Instance.GetFiles("/storage/emulated/0/DCIM/Camera", true); //Its a string list, include the files name


                var inc = 0;

                foreach (var item in picList)
                {

                    var byteArray = FileSystem.Instance.ReadFile("/storage/emulated/0/DCIM/Camera", item.Split('/').Last(), true);

                    var toPicture = ImageSource.FromStream(() => new MemoryStream(byteArray));

                    var image = new Image
                    {
                        ClassId = inc.ToString(),
                        Source = toPicture,
                        WidthRequest = 200,
                        HeightRequest = 200,
                    };
    `        }
    }

我想我需要处理它,但我不知道如何处理。

很可能您从未在映像实例上调用
image.dispose()
方法,所以分配给映像的内存从未释放。你也应该考虑不加载所有文件,但按需加载它们。

我认为你应该在循环之外声明变量并重用它们,而不是在每次迭代时声明新的变量:

byte[] byteArray = null;
MemoryStream toPicture = null;
Image image = null;  

foreach (var item in picList)
{
    byteArray = FileSystem.Instance.ReadFile("/storage/emulated/0/DCIM/Camera", item.Split('/').Last(), true);

    toPicture = ImageSource.FromStream(() => new MemoryStream(byteArray));

    image = new Image
    {
        ClassId = inc.ToString(),
        Source = toPicture,
        WidthRequest = 200,
        HeightRequest = 200,
    };
}

不工作(在本例中,只有一张图片。最后一张。此代码对创建的图像没有任何作用,只是对您编写的循环进行了优化。OutOfMemoryException是否仍然发生?不再出现OutOfMemoryException。如果图片太多且尺寸太大,则UI速度太慢且滞后,UI无法加载所有图片。I h我不知道你的用户界面是如何工作的,请解释一下你在图像加载后是如何处理的。不幸的是,我需要加载所有文件。你知道吗?如果你的用户使用的任何一款手机,我知道它有大约2G的RAM(比如说,考虑到操作系统和其他应用程序,你可以使用一半的内存)还有一款相机,能够以每像素3字节的速度拍摄12像素的图像,每幅图像可以显示36M的图像,这样你就可以加载大约25幅图像,而不需要做任何其他事情。你的要求是不现实的。