Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetPrintJobInfoCollection() Exception sometimes

This code that might seem useless it reproduces the problem. Another application is using http://printqueuewatch.codeplex.com/ to be notified when a print job is sent to printer. It works but sometimes when you send a print job it crashes here GetPrintJobInfoCollection. I have pasted the inner exception. To reproduce I send with Notepad++ or my application a small text file about 20 times until i get a crash. If after the crash I call GetPrintJobInfoCollection it works successfully or I retry.

Any suggestion how to fix this ?

while (true)
{
    Thread.Sleep(10);

    LocalPrintServer server = new LocalPrintServer();

    var q = server.GetPrintQueue("vp1");
    q.Refresh();
    // Debug.WriteLine(q.IsBusy);
    PrintJobInfoCollection infos = null;
    infos = q.GetPrintJobInfoCollection();
}

Error in

System.NullReferenceException was unhandled   Message=Object reference
not set to an instance of an object.   Source=System.Printing  
StackTrace:
    at MS.Internal.PrintWin32Thunk.AttributeNameToInfoLevelMapping.InfoLevelCoverageList.Release()
    at MS.Internal.PrintWin32Thunk.EnumDataThunkObject.GetPrintSystemValuesPerPrintJobs(PrintQueue
printQueue, Queue`1 printObjectsCollection, String[] propertyFilter,
UInt32 firstJobIndex, UInt32 numberOfJobs)
    at System.Printing.PrintJobInfoCollection..ctor(PrintQueue printQueue, String[] propertyFilter)
    at System.Printing.PrintQueue.GetPrintJobInfoCollection()
    at WpfApplication7.MainWindow.button2_Click(Object sender, RoutedEventArgs e) in
like image 335
GorillaApe Avatar asked Aug 14 '13 22:08

GorillaApe


1 Answers

According to this MSDN article you shouldn't use System.Printing namespace.

Classes within the System.Printing namespace are not supported for use within a Windows service or ASP.NET application or service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions. If you want to print from a Windows Forms application, see the System.Drawing.Printing namespace.

I am thinking that your problem is due to resource leak. The LocalPrintServer class seems to be an unmanaged resource and needs to be disposed.

like image 76
Sparrow Avatar answered Oct 16 '22 18:10

Sparrow