tags:

views:

60

answers:

2

Hi

I want to print a html page from c# application but on a back ground thread because if I print the doc on main thread UI freezes for few seconds and I dont want that.

I have tried WebBrowser control but it need to be hosted on some form to get it work. Hosting this control is still acceptable but Print method needs to be called from same thread the control was created on. I tried calling Print method of WebBrowser from other thread but it neither work nor it give any error/exception. I have also tried InternetExplorerClass but it start iexplorer.exe and takes too much time.

Is there any other way in which I can print html page on a diffrent (non UI) thread?

+1  A: 

I'd use a backgroundworker for this purpose - since you've already got a winform and everthing. Drag a background worker and a webbrowser to your form and you can use the following code (UI freezes for milliseconds when the print is actually spooled); I've used a test button (2) for the call;

using System.Threading;

    private void button2_Click(object sender, EventArgs e)
    {
        if (!this.backgroundWorker1.IsBusy)
        {
            this.backgroundWorker1.RunWorkerAsync("http://www.stackoverflow.com/");
        }
        else
        {
            MessageBox.Show("Already working on that piece of paper!");
        }
    }
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        this.webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
        this.webBrowser1.Navigate((string)e.Argument);
        //-- only when you need to read very bulky pages: Thread.Sleep(1000);
        e.Result = true;
    }
    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        this.webBrowser1.Print();
    }
    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        this.webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
    }
riffnl
This code contains a race condition between adding and removing the document completed event handler. That is why you need the Thread.Sleep(1000). And does the Print method not still run on the main thread and not the background worker?
Asher
I am experiencing some delay for the first time. From second time onwards it is working as expected.Is there any way to reduce / remove that delay?
Ram
A: 

Does something like this not work?

webBrowser1.BeginInvoke((MethodInvoker)delegate{webBrowser1.Print();});

Asher