我想在我的C#应用程序中拥有多个gecko浏览器。
所以我做了什么:
FORM UI代码:
public partial class GeckoBrowserForm : Form
{
static GeckoBrowserForm()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
}
public GeckoBrowserForm(string xulRunnerPath, string url)
{
InitializeXulRunner(xulRunnerPath);
m_Url = url;
FormBorderStyle = FormBorderStyle.FixedToolWindow;
ShowInTaskbar = false;
StartPosition = FormStartPosition.Manual;
Location = new Point(0, 0);
Size = new Size(800, 800);
Done = false;
InitializeComponent();
}
private static void InitializeXulRunner(string path)
{
if (!Xpcom.IsInitialized)
{
Xpcom.Initialize(path);
}
}
protected override void OnLoad(EventArgs e)
{
m_GeckoWebBrowser.Parent = this;
m_GeckoWebBrowser.Dock = DockStyle.Fill;
m_GeckoWebBrowser.DocumentCompleted += (s, ee) =>
{
var geckoDomElement = m_GeckoWebBrowser.Document.DocumentElement;
if (geckoDomElement is GeckoHtmlElement)
{
GeckoHtmlElement element = (GeckoHtmlElement)geckoDomElement;
DocumentDomHtml = element.InnerHtml;
}
if (m_Url.Equals(m_GeckoWebBrowser.Document.Url.ToString(), StringComparison.OrdinalIgnoreCase))
{
Done = true;
}
};
m_GeckoWebBrowser.Navigate(m_Url);
}
并且在工作线程中,而不是UI:
if (Xpcom.IsInitialized)
{
Xpcom.Shutdown();
}
using (GeckoBrowserForm geckoBrowserForm = new GeckoBrowserForm(XulRunnerPath, propertyBag.ResponseUri.ToString()))
{
geckoBrowserForm.Show();
while (!geckoBrowserForm.Done)
{
Application.DoEvents();
}
string html = geckoBrowserForm.DocumentDomHtml;
if (!string.IsNullOrEmpty(html))
{
propertyBag.GetResponse = () => new MemoryStream(Encoding.UTF8.GetBytes(html));
}
base.Process(crawler, propertyBag);
}
问题是,在我使用Xpcom.Shutdown();
之后,我再也无法使用Xpcom.Initialize(path);
了。程序刚刚停止而没有任何错误。
为什么?
我知道geckoFx只能在同一个UI线程中使用,我想再次初始化它
public static void AssertCorrectThread()
{
if (Thread.CurrentThread.ManagedThreadId != _XpcomThreadId)
{
throw new InvalidOperationException("GeckoFx can only be called from the same thread on which it was initialized (normally the UI thread).");
}
}
答案 0 :(得分:0)
看来这仍然是一个问题,在单元测试时非常重要。运行所有单元测试(以初始化开始),一切都很好。尝试再次运行它们,并且可能会遇到问题,具体取决于xpCom的状态,因为无法关闭。