title: Windows Service: The calling thread cannot access this object because a different thread owns it
body: <p>Trying to convert XML files using XSL and printing the output. However, receiving the following message: The calling thread cannot access this object because a different thread owns it.</p>
  
  <p>To set an interval for checking files, added a timer to the OnStart.</p>
  
  <pre><code>            if (findPrinter() &gt; 0)
              {
                  System.Timers.Timer printNetterCheck = new System.Timers.Timer();
                  printNetterCheck.Elapsed += new ElapsedEventHandler(OnTimedEvent);
  
                  printNetterCheck.Interval = 30000;
                  printNetterCheck.Enabled = true;
              }
  </code></pre>
  
  <p>The OnTimedEvent:</p>
  
  <pre><code>    private void OnTimedEvent(object source, ElapsedEventArgs e)
      {            
          getFiles();
      }
  </code></pre>
  
  <p>If any files available, call print:</p>
  
  <pre><code>            foreach (string file in files)
              {
                  try
                  {
                      StringWriter xslTransformResult = new StringWriter();
                      XslCompiledTransform xslt = new XslCompiledTransform();
                      xslt.Load(xslPath);
                      xslt.Transform(file, null, xslTransformResult);
  
                      if (print(xslTransformResult) == 1)
                      {
                                //do some things
  </code></pre>
  
  <p>The print function:</p>
  
  <pre><code>    private int print(StringWriter transformedXML)
      {
          //assume OK
          int rc = 1;
  
          try
          {
              StringReader printNetterStreamReader = new StringReader(transformedXML.ToString());
              PrintSystemJobInfo printNetterJob = printer.AddJob("PrintNetterPrint");
  
              Stream printNetterStream = printNetterJob.JobStream;
  
  
              Byte[] printNetterByteBuffer = UnicodeEncoding.Unicode.GetBytes(printNetterStreamReader.ReadToEnd());
  
              printNetterStream.Write(printNetterByteBuffer, 0, printNetterByteBuffer.Length);
              printNetterStream.Close();
          }
          catch (Exception e)
          {
              //return fail
              rc = -1;
              eventLog.WriteEntry("Error printing: " + e.Message, EventLogEntryType.Error);
          }
  
          return rc;
  
      }
  </code></pre>
  
  <p>When calling print I receive the thread error. Found some stuff about Dispatchers etc.. but those are not available when using services.</p>