I am trying to create a GUI program that generates HTML invoices and sends them for printing.
It works for me. However, now I want to introduce threading.
I have a form with BackgroundWorker . The working column runs this code:
#region BackGroundWorker private void bg_htmlGeneration_DoWork(object sender, DoWorkEventArgs e) { //SOME MORE CODE.. foreach (XElement ele in Lib.GetInvoiceElement(inv, ico.Supplier)) { PrintDocument(Lib.CreateHTMLFile()); } } #endregion public void PrintDocument(string fileName) { var th = new Thread(() => { WebBrowser webBrowserForPrinting = new WebBrowser(); webBrowserForPrinting.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(PrintDocumentHandler); webBrowserForPrinting.Url = new Uri(fileName); Application.Run(); }); th.SetApartmentState(ApartmentState.STA); th.Start(); } public void PrintDocumentHandler(object sender, WebBrowserDocumentCompletedEventArgs e) { ((WebBrowser)sender).Print(); ((WebBrowser)sender).Dispose(); Application.ExitThread(); }
Everything goes fine. However, the WebBrowser object refuses to print. No errors (this is obvious), the program ends with nothing sent to the printer.
When I pick up the thread, the program runs again.
My knowledge of streaming is weak, and I teach myself quite a lot - therefore, apparently, I do not understand how the priority of threads is given.
Here How it should work:
- The user selects the invoice on the main form, selects the print.
- The background stream disappears and prints them while the user continues to work on the program.
Any ideas would be appreciated.
source share