如何正确取消在后台STA线程上运行的打印任务?[请注意:这个问题在我的另一个问题中得到了有效解决:Howtocancelbackgroundprintingusingcanceltokensource]我一直在使用以下方法(来自SO)在后台线程上运行我的打印机和打印预览:publicstaticTaskStartSTATask(Actionfunc){vartcs=newTaskCompletionSource();varthread=newThread(()=>{try{func();tcs.SetResult(null);}catch(Exceptione){tcs.SetException(e);}});thread.SetApartmentState(ApartmentState.STA);thread.Priority=ThreadPriority.AboveNormal;线程。开始();返回tcs.Task;它工作完美,没有错误。我不知道如何正确取消此任务。我应该完全中止线程还是传入CancellationTokenSource令牌?如何更改上述代码以允许取消(或中止)?我不知所措。感谢您对此的任何帮助。(经过多次谷歌搜索,这里的解决方案根本不像我希望的那样简单!)经过深思熟虑,我倾向于将CancellationToken传递给正在执行的func(),并强制终止该函数。在这种情况下,这意味着关闭PrintDialogue()。还有另一种方式吗?..//打印预览文档。chartlabels.PrintPreview(fixeddocument);});}//打印预览publicstaticvoidPrintPreview(FixedDocumentfixeddocument){MemoryStreamms=newMemoryStream();使用(Packagep=Package.Open(ms,FileMode.Create,FileAccess.ReadWrite)){Uriu=newUri("pack://TemporaryPackageUri.xps");PackageStore.AddPackage(u,p);XpsDocumentdoc=newXpsDocument(p,CompressionOption.Maximum,u.AbsoluteUri);XpsDocumentWriterwriter=XpsDocument.CreateXpsDocumentWriter(doc);writer.Write(fixeddocument.DocumentPaginator);/*没有自定义预览器的工作替代方案//在DocViewer中查看varpreviewWindow=newWindow();vardocViewer=newDocumentViewer();//System.Windows.Controls.DocumentViewer类。previewWindow.Content=做c查看器;固定文档序列fixedDocumentSequence=doc.GetFixedDocumentSequence();docViewer.Document=fixedDocumentSequence作为IDocumentPaginatorSource;//ShowDialog-在顶部打开一个窗口,只有在新打开的窗口关闭时才返回。doc.GetFixedDocumentSequence();//使用我的自定义文档查看器(删除了打印按钮)。varpreviewWindow=newPrintPreview(fixedDocumentSequence);previewWindow.ShowDialog();PackageStore.RemovePackage(u);文档.Close();希望它有助于更??好地解释我的问题以上是C#学习教程:如何正确取消在后台STA线程上运行的打印任务?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
