GetPrintJobInfoCollection()有时会出现异常

Gor*_*Ape 6 .net c# printing xpsdocument xps

这段代码似乎无用,它可以重现问题.另一个应用程序是使用 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();
}
Run Code Online (Sandbox Code Playgroud)

错误

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
Run Code Online (Sandbox Code Playgroud)

Spa*_*row 1

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

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

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