多线程 - 等到对象初始化?

时间:2016-04-26 20:02:38

标签: c# multithreading webbrowser-control

主线程中的代码:

browser = new System.Windows.Forms.WebBrowser();
Thread subthread = new Thread(new ThreadStart(testfn));
subthread.Start();

主题:

void testfn(){
    string lastttl="";
    while (true) {
        System.Threading.Thread.Sleep(500);
        if (browser == null) continue;
        browser.Invoke(new Action(() => ttlstr = browser.Document.Title));
        if (ttlstr != lastttl) { lastttl = ttlstr; MessageBox.Show("title changed to: '" + ttlstr + "'"); }
    }
}

testfn()然后调用browser.Invoke。我没想到这是一个问题,因为browser = new ...应该阻塞直到创建对象(..right?),但我仍然得到一个NullReferenceException。

  • 浏览器最初设置为null
  • 在第二个线程中检查browser == null也会抛出空引用异常
  • 在启动线程之前添加while(browser == null){System.Threading.Thread.Sleep(5);}也无济于事

0 个答案:

没有答案