views:

50

answers:

0

I'm running a webbrowser form inside an asp.net WCF web service. I'm creating a second thread for the webbrowser form and then creating a third thread to run the message loop for the form. My problem is that I can't figure out how to stop the third thread and dispose of the webbrowser form. Without stopping the third thread then the secondThread.join never completes. When I call secondthread.abort this causes the third thread to leak and I end up with a massive amount of leaked threads after a while.

    public class IEBrowser : System.Windows.Forms.ApplicationContext
    {
    public IEBrowser(string userName, string password, AutoResetEvent resultEvent, string url, Boolean resetCookies, Boolean dDebug, String DebugFile)
{

    this.userName = userName;
    this.password = password;
    this.url = url;
    this.resultEvent = resultEvent;
    htmlResult = null;
ths = new ThreadStart(delegate { 
            Init(resetCookies);
            System.Windows.Forms.Application.Run(this);
        });
        thrd = new Thread(ths);
        thrd.Name = "2nd Thread";
        thrd.IsBackground = true;
        // set thread to STA state before starting
        thrd.SetApartmentState(ApartmentState.STA);
        thrd.Start();
    }

    // initialize the WebBrowser and the form
    private void Init(Boolean resetCookies)
    {
            scriptCallback = new ScriptCallback(this);
            // create a WebBrowser control
            ieBrowser = new WebBrowser();
            //Reset Session
            if (resetCookies) { InternetSetOption(IntPtr.Zero, INTERNET_OPTION_END_BROWSER_SESSION, IntPtr.Zero, 0); }
            // set the location of script callback functions
            ieBrowser.ObjectForScripting = scriptCallback;
            // set WebBrowser event handls
            ieBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(IEBrowser_DocumentCompleted);
            ieBrowser.Navigating += new WebBrowserNavigatingEventHandler(IEBrowser_Navigating);
            loginCount = 0;
            // initialise the navigation counter
            navigationCounter = 0;
            ieBrowser.Navigate(url);
    }

    // dipose the WebBrowser control and the form and its controls
    protected override void Dispose(bool disposing)
    {
        if (thrd != null)
        {                
            this.ExitThread();
            thrd.Join();
            thrd = null;
            return;
        }
    }
 }