如何正确取消在后台STA线程上运行的打印任务?

[请注意:这个问题在我的另一个问题中得到了有效解决: 如何使用canceltokensource取消后台打印 ]

我一直在使用以下方法(从SO)运行我的打印机并在后台线程上打印预览:

public static Task StartSTATask(Action func) { var tcs = new TaskCompletionSource(); var thread = new Thread(() => { try { func(); tcs.SetResult(null); } catch (Exception e) { tcs.SetException(e); } }); thread.SetApartmentState(ApartmentState.STA); thread.Priority = ThreadPriority.AboveNormal; thread.Start(); return tcs.Task; } 

它运行完美,没有错误。

我不知道如何适当地取消这个任务。 我应该完全中止线程还是传入CancellationTokenSource令牌? 如何更改上述代码以允许取消(或中止)?

我很迷茫。 感谢您对此的任何帮助。

(经过大量的谷歌搜索,这里的解决方案根本不像我希望的那样微不足道!)

经过深思熟虑后,我倾向于将CancellationToken传递给正在执行的func(),并强制终止该函数。 在这种情况下,这意味着要关闭PrintDialogue()。 还有另一种方式吗?

我使用上面的代码:

  public override Task PrintPreviewAsync() { return StartSTATask(() => { // Set up the label page LabelMaker chartlabels = ... ... create a fixed document... // print preview the document. chartlabels.PrintPreview(fixeddocument); }); } // Print Preview public static void PrintPreview(FixedDocument fixeddocument) { MemoryStream ms = new MemoryStream(); using (Package p = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite)) { Uri u = new Uri("pack://TemporaryPackageUri.xps"); PackageStore.AddPackage(u, p); XpsDocument doc = new XpsDocument(p, CompressionOption.Maximum, u.AbsoluteUri); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc); writer.Write(fixeddocument.DocumentPaginator); /* A Working Alternative without custom previewer //View in the DocViewer var previewWindow = new Window(); var docViewer = new DocumentViewer(); // the System.Windows.Controls.DocumentViewer class. previewWindow.Content = docViewer; FixedDocumentSequence fixedDocumentSequence = doc.GetFixedDocumentSequence(); docViewer.Document = fixedDocumentSequence as IDocumentPaginatorSource; // ShowDialog - Opens a window on top and returns only when the newly opened window is closed. previewWindow.ShowDialog(); */ FixedDocumentSequence fixedDocumentSequence = doc.GetFixedDocumentSequence(); // Use my custom document viewer (the print button is removed). var previewWindow = new PrintPreview(fixedDocumentSequence); previewWindow.ShowDialog(); PackageStore.RemovePackage(u); doc.Close(); } } 

希望它有助于更​​好地解释我的问题。