How to properly cancel a print task running against a STA thread?

[Please note: this issue was effectively resolved in my other question: How to use the undo cancel function to cancel background printing ]

I used the following method (from SO) to start my printers and preview in the background thread:

public static Task StartSTATask(Action func) { var tcs = new TaskCompletionSource<object>(); 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; } 

It works perfectly, without errors.

I do not understand how to cancel this task correctly. Should I completely stop the flow or pass the CancellationTokenSource token? How has the above code changed to allow cancellation (or abort)?

I am very confused. Thanks for any help with this.

(After long searches, the solution here is not at all as trivial as I hoped!)

After I thought, I tend to pass the CancellationToken to the func () executable and force the function to stop working. In this case, this means that PrintDialogue () is closing. Is there another way?

I use the above code as:

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

Hope this helps to better explain my problem.

0
source share

Source: https://habr.com/ru/post/1012970/


All Articles