Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7093049
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T08:23:26+00:00 2026-05-28T08:23:26+00:00

I have a set of threaded classes that print different types of documents. The

  • 0

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).

  1. The Note appears to suggest that using try{} ... catch{} is NEVER safe inside a thread if the thread can be Abort()‘ed. Is this true?
  2. I do not see how I can avoid using Abort() in my scenario. Will using Thread.Interrupt() instead make any difference?
  3. 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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T08:23:27+00:00Added an answer on May 28, 2026 at 8:23 am

    I think I found a solution by making the following changes:

    1. Do not call Thread.Abort() if we know that the worker thread is executing a catch{} block (see protected volatile bool isPrinting below).
    2. Use a separate thread to call Thread.Abort() and encourage a context switch with Sleep(0) (see private void AbortPrintWorker() below).

      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; }
      
          protected System.Threading.Thread worker;
          protected volatile bool isPrinting;
      
          public void Print()
          {
              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
              {
                  AbortPrintWorker();
                  printOk = false;
                  Logging.Log("Timed out waiting for " + applicationName + " file " + filename + " to print.", Logging.LogLevel.Error);
              }
          }
          protected abstract void printWorker();
      
          public abstract void Dispose();
      
          private void AbortPrintWorker()
          {
              System.Threading.Thread abortThread = new System.Threading.Thread(abortWorker);
              if (isPrinting)
              {
                  abortThread.Start();
                  System.Threading.Thread.Sleep(0);
                  abortThread.Join();
              }
              else
              {
                  worker.Join();
              }
          }
      
          private void abortWorker()
          {
              worker.Abort();
              worker.Join();
          }
      }
      
      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
              {
                  isPrinting = true;
      
                  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;
      
                  isPrinting = true;
              }
              catch (System.Exception ex)
              {
                  isPrinting = false;
      
                  Logging.Log("Unable to print PowerPoint file " + filename + ". Exception: " + ex.Message, Logging.LogLevel.Error);
                  workerPrintOk = false;
              }
          }
      
          public override void Dispose()
          {
              try
              {
                  if (officePowerPoint != null)
                      officePowerPoint.Quit();
                  Marshal.FinalReleaseComObject(officePowerPoint);
                  officePowerPoint = null;
                  if (KillApplicationOnClose)
                      Utility.KillProcessesByName(OfficePowerPointExe);
              }
              catch { }
          }
      }
      

    AbortPrintWorker() creates a separate thread to call Abort() on the worker thread. I believe this deals with the issue highlighted in the Note on Abort():

    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.

    Is this correct?

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We have a helper class that we use to call stored procs on SQL
I have set up transactional replication between two SQL Servers on different ends of
I have set up a Django application that uses images. I think I have
I have set of scripts for doing scripted installs. You can use the scripts
I have a set of classes in a logging framework used by project A
I have a multi-threaded Delphi 6 Pro application that I am currently working on
I have been working on a project where I have a Worker class that
I have a XAML form that I would like two independent features threaded out
OpenSSL documents state that it can safely be used in multi-threaded applications provided that
I have a multi-threaded Delphi program creating multiple instance of some classes, and I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.