GetPrintJobInfoCollection()有时会出现异常



这段看似无用的代码再现了问题。另一个应用程序正在使用http://printqueuewatch.codeplex.com/以在将打印作业发送到打印机时得到通知。它可以工作,但有时当您发送打印作业时,它会在GetPrintJobInfoCollection中崩溃。我已经粘贴了内部异常。为了重现,我用Notepad++或我的应用程序发送了大约20次小文本文件,直到我崩溃。如果崩溃后我调用GetPrintJobInfoCollection,它会成功工作,或者我会重试。

有什么建议吗?

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();
}

错误

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

根据MSDN的这篇文章,您不应该使用System.Printing命名空间。

System.Printing命名空间中的类不支持使用在Windows服务或ASP.NET应用程序或服务中。正在尝试在其中一种应用程序类型中使用这些类可能产生意想不到的问题,例如服务性能下降以及运行时异常。如果要从Windows窗体打印应用程序,请参见System.Drawing.Printing命名空间。

我认为你的问题是由于资源泄漏造成的。LocalPrintServer类似乎是一个非托管资源,需要释放。

最新更新