title: word automation printout: wait for its finished?
body: <p>I'm using word automation to generate a docx file, then print it out. Here is my basic code. I found that I have to wait some time after adoc.PrintOut, otherwise, the print may fail. It seems it is because I close the file after that. Before the file is closed, word does not have time to print it out yet. So, basically, adoc.PrintOut is non-blocked (this may not be the correct term). Right now, I wait for 10 seconds, it works fine. However, does it have a more elegant solution for this? I mean, how can wait until PrintOut finished, then close the doc?</p>
  
  <p>thanks</p>
  
  <pre><code>object yes = true;
  object no = false;           
  object missing = System.Reflection.Missing.Value;
  
  
  Word.Application wordApp = new Word.Application();
  
  object fileName = originalFileName;
  Word.Document adoc = null;
  try
  {
      adoc = wordApp.Documents.Open(ref fileName,
              ref missing, ref no, ref missing,
              ref missing, ref missing, ref  missing, ref  missing, ref  missing,
              ref  missing, ref missing, ref yes, ref  missing, ref  missing, ref  missing, ref  missing);
  
      adoc.Activate();
  
      /* 
          some other processing
      */
  
  
  
      object sFile = fileName;
  
      adoc.PrintOut(ref missing, ref missing, ref  missing, ref  missing, ref  missing, ref missing, ref missing, ref  missing, ref  missing, ref  missing, ref missing, ref missing, ref missing, ref  missing, ref  missing, ref  missing, ref missing, ref missing);
  
      // http://msdn.microsoft.com/en-us/library/b9f0ke7y
      //adoc.PrintPreview();
  
      for (int i = 0; i &lt; 10; i++)
      {
          Thread.Sleep(TimeSpan.FromSeconds(1));
          Application.DoEvents();
      }
      //adoc.Save();
  
      object savechanges = Word.WdSaveOptions.wdDoNotSaveChanges; //.wdSaveChanges;
      object originalFormat = Word.WdOriginalFormat.wdWordDocument;
      object routeDocument = missing; // Type.Missing; // true;
  
      ((Word._Document)adoc).Close(ref savechanges, ref originalFormat, ref routeDocument);
  
      ((Word._Application)wordApp).Quit(ref savechanges, ref missing, ref missing);
  
      adoc = null;
      wordApp = null;
  }
  catch
  {
  
  }
  finally
  {
      /*
          some dispose work       
      */
  
      // do it twice to release all memory
      GC.Collect();
      GC.WaitForPendingFinalizers();
      GC.Collect();
      GC.WaitForPendingFinalizers();
  
  }
  </code></pre>