首页 > 解决方案 > using(Bitmap) 偶尔并行抛出异常

问题描述

我正在尝试一次从街景全景图中下载并保存多个 bmp。在正常的 for 循环中使用 Panorama() 可以正常工作,但是当我将它放在 Parallel.For 中时,它会在大约 20 张带有无效参数异常的图像后抛出异常,using (Bitmap result = new Bitmap(26 * 512, 13 * 512))并被高亮显示。崩溃时内存使用量为 4GB,但这应该不是问题,因为我有 16GB 的 RAM。

这是我的代码:

        public static void AllPanoramas((double Lat, double Lon)[] locData, string folderPath, ImageFormat format)
    {
        ServicePointManager.DefaultConnectionLimit = Environment.ProcessorCount * 12;

        string[] panoIDs = new string[locData.Length];
        Parallel.For(0, locData.Length, i =>
        {
            panoIDs[i] = Web.GetPanoID(locData[i], 50);
        });

        Parallel.For(0, panoIDs.Length, i =>
        {
            Panorama(panoIDs[i], folderPath + @"\image" + i + "." + format.ToString().ToLower(), format);
        });
    }

    public static void Panorama(string panoID, string file, ImageFormat format)
    {
        Image[,] images = new Image[26, 13];
        Parallel.For(0, 26, x => {
            Parallel.For(0, 13, y =>{
                using (WebClient client = new WebClient())
                    images[x, y] = Image.FromStream(new MemoryStream(client.DownloadData(Get.TileURL(panoID, x, y))));
            });
        });

        using (Bitmap result = new Bitmap(26 * 512, 13 * 512))
        {
            for (int x = 0; x < 26; x++)
                for (int y = 0; y < 13; y++)
                    using (Graphics g = Graphics.FromImage(result))
                        g.DrawImage(images[x, y], x * 512, y * 512);
            result.Save(file, format);
        }
    }

我不确定是什么导致了这个问题,所以任何帮助都将不胜感激。

标签: c#imageparallel-processingbitmappanoramas

解决方案


这样做的原因是我正在构建 32 位,这意味着我可以使用的最大内存是 4GB。将其更改为 64 位解决了问题。


推荐阅读