patterncsharpMajor
Printing 300 pages
Viewed 0 times
300pagesprinting
Problem
I have a problem with my printing program, in which it uses up too much resources while printing (to paper or to .pdf). I try to manually dispose as much as I can, but for example, when I tried printing 300 pages, the program itself used up around 500mb of memory, and I would like to avoid that. When the program finishes printing, it goes back down to 37mb of usage. I use Visual Studio to check performance. Below you can find the code, and any help to manage resources and lower ram usage while printing would be appreciated. I apologize in advance for mixing German and English. And for clarity, this draws n number of each element (one is a string, second an arrow, up or down, third a barcode).
private void DocumentDrucker_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Graphics graphic = e.Graphics;
SolidBrush brush = new SolidBrush(Color.Black);
Font font = new Font("Courier New", 27, FontStyle.Bold);
float pageWidth = e.PageSettings.PrintableArea.Width;
float pageHeight = e.PageSettings.PrintableArea.Height;
float fontHeight = font.GetHeight();
int startX = 40;
int startY = 40;
int offsetY = 40;
for (; elemente = pageWidth-100)
{
e.HasMorePages = true;
offsetY = 0;
elemente++;
graphic.Dispose();
b.Dispose();
brush.Dispose();
font.Dispose();
return;
}
else
{
e.HasMorePages = false;
}
}
graphic.Dispose();
b.Dispose();
brush.Dispose();
font.Dispose();
}Solution
I try to manually dispose as much as I can
This is usually good however this time you dispose too much.
You receive the
This is usually good however this time you dispose too much.
private void DocumentDrucker_PrintPage(object sender, PrintPageEventArgs e)
{
Graphics graphic = e.Graphics;
..
graphic.Dispose(); // Don't!
}You receive the
Graphics object via the PrintPageEventArgs. This means that you should not dispose it. The owner takes care of the graphics object. You just use it for drawing. I wonder that this works at all because as soon as the graphics is disposed the DocumentDrucker has nothing to print. This should actually crash.Code Snippets
private void DocumentDrucker_PrintPage(object sender, PrintPageEventArgs e)
{
Graphics graphic = e.Graphics;
..
graphic.Dispose(); // Don't!
}Context
StackExchange Code Review Q#162466, answer score: 20
Revisions (0)
No revisions yet.