I'm already aware of the fact that PrintDocument.Print() is not threadsafe. To circumvent this problem I'm doing the printing in a separate thread. Unfortunately this does not help. I'm getting an ArgumentException:
- Code: Select all
System.ArgumentException: Ein Element mit dem gleichen Schlüssel wurde bereits hinzugefügt.
bei System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
bei System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
bei sprᮌ.ᜂ()
bei sprᮌ.ᜁ(Single A_0)
bei sprᮌ.ᜂ(Single A_0)
bei sprᲅ.ᜀ(Graphics A_0, spr᫊ A_1, Boolean A_2)
bei sprᲅ.ᜁ(Graphics A_0, spr᫊ A_1, Boolean A_2)
bei spr᫊.ᜀ(String A_0, sprᮌ A_1, String A_2, Boolean A_3)
bei spr᫊.ᜀ(String[] A_0, String A_1)
bei spr᫊.ᜀ(sprᰡ A_0)
bei spr᫊.ᜇ(Boolean A_0)
bei spr᫊.ᜟ()
bei Spire.Pdf.PdfDocument.ᜀ(Object A_0)
bei Spire.Pdf.PdfDocument.OnPrintPage(Object sender, PrintPageEventArgs e)
bei System.Drawing.Printing.PrintDocument.OnPrintPage(PrintPageEventArgs e)
bei System.Drawing.Printing.PrintDocument._OnPrintPage(PrintPageEventArgs e)
bei System.Drawing.Printing.PrintController.PrintLoop(PrintDocument document)
bei System.Drawing.Printing.PrintController.Print(PrintDocument document)
bei System.Drawing.Printing.PrintDocument.Print()
bei MobileIQ.PrintService.ConsumerService.Tools.Printer.<>c__DisplayClass1.<Print>b__0()
bei MobileIQ.PrintService.ConsumerService.Tools.StaTasks.<>c__DisplayClass4.<StartStaTask>b__3()
I have a german Windows, hence the german error message. The translation is:
- Code: Select all
Argument Exception: Item with Same Key has already been added
This means for me: Either I did something wrong in my code or running the Print method in a different thread is not sufficient.
My Question: How can I print a PDF document with Spire.PDF in a threadsafe way? Is it even possible?
I'm usung Spire.PDF 3.4.27.
Best Regards
Olaf
Here are the relevant code snippets:
- Code: Select all
public static void Print(string printerName, string document)
{
var task = StaTasks.StartStaTask(() =>
{
using (var doc = new PdfDocument())
{
doc.LoadFromFile(document);
doc.PrinterName = printerName;
var printDoc = doc.PrintDocument;
printDoc.Print();
}
});
task.Wait();
}
- Code: Select all
public static Task StartStaTask(Action action)
{
var tcs = new TaskCompletionSource<object>();
var thread = new Thread(() =>
{
try
{
action();
tcs.SetResult(null);
}
catch (Exception e)
{
tcs.SetException(e);
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
return tcs.Task;
}