Using code to create control objects, set the event listening method does not execute

This is in a WinForm program, click a button on the interface to generate another thread, generate WebBrowser control, and increase event monitoring

private void button1_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(m)); t.Start();
        }

        private void m()
        {
            WebBrowser w = new WebBrowser();
            w.DocumentCompleted +=new WebBrowserDocumentCompletedEventHandler(w_DocumentCompleted);
            w.Navigate("www.baidu.com");
        }

        private void w_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            MessageBox.Show("OK");
        }

When the program is running, you can find that there is no ok window pop-up. If you set the breakpoint, you will find that there is no w at all_ Run in the documentcompleted method. The reason is that the thread of the browser ends after executing the m method, and there is no time to execute the event listening method. At this point, there is a way to use the message box to make the thread temporarily not disappear

private void button1_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(m));
            t.ApartmentState = ApartmentState.STA;
            t.Start();
        }

        private void m()
        {
            WebBrowser w = new WebBrowser();
            w.DocumentCompleted +=new WebBrowserDocumentCompletedEventHandler(w_DocumentCompleted);
            w.Navigate("www.baidu.com");
            MessageBox.Show("AAA");
        }

        private void w_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            MessageBox.Show("OK");
        }

Now, if the thread does not disappear after AAA, then the event will be monitored and OK will appear


Read More: