Here’s a snippet of code I have to print a document in WPF. At a high level, I instantiate a UserControl, and then send it to a printer.
var printQueue = GetQueues().Where(t => t.Name == comboBox1.SelectedItem.ToString()).FirstOrDefault();
var defaultPrintTicket = printQueue.DefaultPrintTicket.Clone();
var newTicket = ModifyPrintTicket(defaultPrintTicket, "psk:JobInputBin",
((PrintTrays)listBox1.SelectedItem).ConfigValue);
var xpsWriter = PrintQueue.CreateXpsDocumentWriter(printQueue);
var controlToPrint = new PackingSlip();
var fixedDoc = new FixedDocument();
var pageContent = new PageContent();
var fixedPage = new FixedPage();
fixedPage.Children.Add(controlToPrint);
((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage);
fixedDoc.Pages.Add(pageContent);
xpsWriter.Write(fixedDoc, newTicket);
What I’m wondering about is that over time, I’ll have created hundreds of the instances of controlToPrint. Am I going to run into memory issues here, or do they get disposed of automatically in some fashion? If they aren’t disposed automatically, how would I free up that memory?
They will be disposed of automatically assuming that fixedDoc, fixedPage, pagecontent and controlToPrint go out of scope at the end of the method. If application roots hold onto any reference to any of those objects then you will get a memory leak