Can someone explain why this code:
public static void Main()
{
int times = 9999;
Parallel.For(1, times, i =>
{
using (Image img = new Bitmap(times, 1600))
{
using (Image resized = new Bitmap(img, 10, 10))
{
Console.WriteLine(i);
}
}
});
}
Gives the following error?
System.AggregateException: One or more errors occurred. ---> System.ArgumentException: Parameter is not valid.
Result StackTrace:
at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, PixelFormat format)
at System.Drawing.Bitmap..ctor(Int32 width, Int32 height)
I believe the problem is to do with memory usage. I realise I'm making a lot of images all at once, but since each of the images are in a using statement, they should be disposed of correctly?
I realise I've simplified the actual method quite a bit - what this really is, is a unit test. Given an image being created, I'm resizing based on a width, and testing that my code can handle being run in a thread, however it's falling over on the test (above).
UPDATE: This fails:
int times = 9999;
Parallel.For(1, times, i =>
{
using (Image img = new Bitmap(times, 1600))
{
using (Bitmap resized = new Bitmap(img, img.Width, img.Height))
{
//Some code...
int width = resized.Width;
}
}
});
But this works (note the missing image parameter in the second bitmap constructor):
int times = 9999;
Parallel.For(1, times, i =>
{
using (Image img = new Bitmap(times, 1600))
{
using (Bitmap resized = new Bitmap(img.Width, img.Height))
{
//Some code...
int width = resized.Width;
}
}
});
Any ideas why one works and the other doesn't when they're nearly identical? They both create very large images, both are in using statements to correctly dispose the images, but only the first one is creating an image from an existing image. Why should this make a difference?