I have a set of threaded classes that print different types of documents. The classes use inheritance to share common code. The class constructor requires file name and printer name arguments. A Print()
method creates a new worker thread, waits for the worker thread to complete using Thread.Join(timeout)
and calls Thread.Abort()
on the worker thread if the Join
times out. The worker thread starts an application that can open the specified file, causes the file to be sent to printer synchronously (usually using application's Print method) and exits. The worker thread's code is wrapped in a try{} ... catch{}
block to deal with any unforeseen crashes of the external application. The catch block contains minimal cleanup and logging.
internal static FilePackage TryPrintDocumentToPdf(string Filename)
{
.....
Logging.Log("Printing this file using PowerPoint.", Logging.LogLevel.Debug);
printableFormat = true;
fc = new FileCollector(Email2Pdf.Settings.Printer.PdfAttachmentCollectDirectoryObj, FileCollector.CollectMethods.FileCount | FileCollector.CollectMethods.FilesNotInUse | FileCollector.CollectMethods.ProcessExit);
fc.FileCount = 1;
fc.ProcessNames = new string[] { OfficePowerPointExe, Email2Pdf.Settings.Printer.PrinterExe };
fc.Prepare();
using (PowerPointPrinter printer = new PowerPointPrinter(Filename, Email2Pdf.Settings.Printer.PdfAttachmentPrinter))
{
printer.KillApplicationOnClose = true;
printer.Print();
printOk = printer.PrintOk;
}
.....
}
internal abstract class ApplicationPrinter : IDisposable
{
protected abstract string applicationName { get; }
protected string filename;
protected string printer;
protected bool workerPrintOk;
protected bool printOk;
public bool PrintOk { get { return printOk; } }
public bool KillApplicationOnClose { get; set; }
public void Print()
{
System.Threading.Thread worker = new System.Threading.Thread(printWorker);
DateTime time = DateTime.Now;
worker.Start();
if (worker.Join(new TimeSpan(0, Email2Pdf.Settings.Printer.FileGenerateTimeOutMins, 0)))
{
printOk = workerPrintOk;
}
else
{
worker.Abort();
printOk = false;
Logging.Log("Timed out waiting for " + applicationName + " file " + filename + " to print.", Logging.LogLevel.Error);
}
}
protected abstract void Close();
protected abstract void printWorker();
public virtual void Dispose() { Close(); }
}
internal class PowerPointPrinter : ApplicationPrinter
{
private const string appName = "PowerPoint";
protected override string applicationName { get { return appName; } }
private Microsoft.Office.Interop.PowerPoint.Application officePowerPoint = null;
public PowerPointPrinter(string Filename, string Printer)
{
filename = Filename;
printer = Printer;
this.Dispose();
}
protected override void printWorker()
{
try
{
officePowerPoint = new Microsoft.Office.Interop.PowerPoint.Application();
officePowerPoint.DisplayAlerts = Microsoft.Office.Interop.PowerPoint.PpAlertLevel.ppAlertsNone;
Microsoft.Office.Interop.PowerPoint.Presentation doc = null;
doc = officePowerPoint.Presentations.Open(
filename,
Microsoft.Office.Core.MsoTriState.msoTrue,
Microsoft.Office.Core.MsoTriState.msoFalse,
Microsoft.Office.Core.MsoTriState.msoFalse);
doc.PrintOptions.ActivePrinter = printer;
doc.PrintOptions.PrintInBackground = Microsoft.Office.Core.MsoTriState.msoFalse;
doc.PrintOptions.OutputType = Microsoft.Office.Interop.PowerPoint.PpPrintOutputType.ppPrintOutputSlides;
doc.PrintOut();
System.Threading.Thread.Sleep(500);
doc.Close();
//Marshal.FinalReleaseComObject(doc);
doc = null;
workerPrintOk = true;
}
catch (System.Exception ex)
{
Logging.Log("Unable to print PowerPoint file " + filename + ". Exception: " + ex.Message, Logging.LogLevel.Error);
Close();
workerPrintOk = false;
}
}
protected override void Close()
{
try
{
if (officePowerPoint != null)
officePowerPoint.Quit();
Marshal.FinalReleaseComObject(officePowerPoint);
officePowerPoint = null;
if (KillApplicationOnClose)
Utility.KillProcessesByName(OfficePowerPointExe);
}
catch { }
}
}
I found my application non-responsive, with the main thread in a Sleep/Wait/Join at the Thread.Abort() line. I do not recall the status of the worker thread, but the logging that was supposed to be performed in the catch{}
block did not take place. (I Attached to my process with VS2010 after I found it non-responsive).
I refer to the following Note from the Thread.Abort Method:
The thread that calls Abort might block if the thread that is being aborted is in a protected region of code, such as a catch block, finally block, or constrained execution region. If the thread that calls Abort holds a lock that the aborted thread requires, a deadlock can occur.
I believe I have a dead-locking issue because (1) it does not always happen, and (2) because of the Note on MSDN (above).
- The Note appears to suggest that using
try{} ... catch{}
is NEVER safe inside a thread if the thread can beAbort()
'ed. Is this true? - I do not see how I can avoid using
Abort()
in my scenario. Will usingThread.Interrupt()
instead make any difference? - How to I fix the dead-locking issue I have?
BackgroundWorker does not work for me because I do not need progress reporting and, more importantly, it is possible that my worker thread will block indefinitely when it executes third party applications. For the same reason, I cannot ask my thread to terminate, but have one option only - to ruthlessly Abort()
the worker thread.
I think I found a solution by making the following changes:
Thread.Abort()
if we know that the worker thread is executing acatch{}
block (seeprotected volatile bool isPrinting
below).Use a separate thread to call
Thread.Abort()
and encourage a context switch withSleep(0)
(seeprivate void AbortPrintWorker()
below).AbortPrintWorker()
creates a separate thread to callAbort()
on the worker thread. I believe this deals with the issue highlighted in the Note onAbort()
:Is this correct?