c# - GetPrintJobInfoCollection() 有时会出现异常

标签 c# .net printing xps xpsdocument

这段看似无用的代码重现了问题。另一个应用程序正在使用 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

最佳答案

根据 this MSDN article你不应该使用 System.Printing 命名空间。

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.

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

关于c# - GetPrintJobInfoCollection() 有时会出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18243519/

相关文章:

c# - .NET 获取自定义配置部分作为 NameValueCollection

java - JComboBox 显示不可见的下拉菜单

c# - 生成给定字符串列表的子列表

c# - 使用 stringbuilder 为数据库报告输出 HTML 可以吗?

c# - 即时生成自签名证书

java - 创建准备打印的图表

C++、win32、gdi 打印 : DrawEdge does not reach as far as DrawText?

c# - Entity Framework 4.1 Code First EDMX 问题

c# - 奇怪的是 SQL Server Management Studio 中的数据

c# - 2D WPF 游戏,我有哪些选择?