I'm using the barcode class to generate and print labels. I ran into an issue where the ToBitmap() was leading to a sort of memory leak. I did a bunch of research and found out that the BitmapSource class has an issue where it will stay in memory until it goes out of scope and the GC collects it. This is all fine and dandy, but when generating a large number images using the lib, the program will quickly crash due to memory usage.
Below is an untested example. In order to prevent the program from eating up to much memory and crashing i've had to call GC.Collect(); and GC.WaitForPendingFinalizers(); which just feels really hacky.
double dpi = double.Parse(textboxDPI.Text.Trim());
int i = 20000000;
while (i != 20010000)
{
Code128Symbology c128 = new Code128Symbology();
c128.QuietZoneThickness = new System.Windows.Thickness(5, 0, 5, 0);
c128.Value = "test-barcode";
c128.BarHeight = 38;
c128.BarWidthRatio = 2;
c128.ValueIntrusionOffset = 5;
c128.ValueDisplayStyle = LinearBarCodeValueDisplayStyle.Centered;
BitmapSource ImageSource = c128.ToBitmap(dpi, dpi);
c128.Dispose();
using (var fileStream = new FileStream(@"C:\Temp\" + Guid.NewGuid() + "_test.png", FileMode.Create))
{
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(ImageSource));
encoder.Save(fileStream);
ImageSource = null;
}
//Hacky GC call to prevent the BitmapSource Memory Leak
//Explicitly call GC and wait for finalizers
System.GC.Collect();
GC.WaitForPendingFinalizers();
i++;
}