这是我的类GeckoBrowserForm
namespace NCrawler.GeckoProcessor
{
public partial class GeckoBrowserForm : Form
{
#region Readonly & Static Fields
private static bool s_IsXulrunnerInitialized;
private readonly GeckoWebBrowser m_GeckoWebBrowser = new GeckoWebBrowser();
private readonly string m_Url;
private SynchronizationContext m_uiContext;
#endregion
#region Constructors
static GeckoBrowserForm()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
}
public GeckoBrowserForm(string xulRunnerPath, string url)
{
m_uiContext = SynchronizationContext.Current;
if (m_uiContext == null)
{
m_uiContext = new SynchronizationContext();
}
InitializeXulRunner(xulRunnerPath);
m_Url = url;
ShowInTaskbar = false;
StartPosition = FormStartPosition.Manual;
Location = new Point(0, 0);
Size = new Size(800, 800);
Done = false;
InitializeComponent();
}
#endregion
#region Instance Properties
public string DocumentDomHtml { get; set; }
public Boolean Done { get; set; }
#endregion
#region Instance Methods
protected override void OnLoad(EventArgs e)
{
Thread thread = new Thread(new ThreadStart(DoWork));
thread.Start();
}
private void DoWork()
{
// lets see the thread id
int id = Thread.CurrentThread.ManagedThreadId;
Trace.WriteLine("Run thread: " + id);
m_uiContext.Send(new SendOrPostCallback(_ =>
{
m_GeckoWebBrowser.Parent = this;
m_GeckoWebBrowser.Dock = DockStyle.Fill;
m_GeckoWebBrowser.DocumentCompleted += (s, ee) =>
{
GeckoHtmlElement element = null;
var geckoDomElement = m_GeckoWebBrowser.Document.DocumentElement;
if (geckoDomElement != null && geckoDomElement is GeckoHtmlElement)
{
element = (GeckoHtmlElement)geckoDomElement;
DocumentDomHtml = element.InnerHtml;
}
};
m_GeckoWebBrowser.Navigate(m_Url);
}), null);
}
#endregion
#region Class Methods
private static void InitializeXulRunner(string path)
{
if (s_IsXulrunnerInitialized)
{
return;
}
s_IsXulrunnerInitialized = true;
Xpcom.Initialize(path);
}
#endregion
}
}
但是DoWork
方法获得了一次删除
GeckoFx只能从它所在的同一个线程中调用 初始化(通常是UI线程)
我已经读过我需要使用SynchronizationContext
,但它是一样的。还是一样的错误。我正在使用
GeckoBrowserForm geckoBrowserForm = new GeckoBrowserForm(XulRunnerPath, Uri.ToString()))
geckoBrowserForm.Show();
并且它在内部线程中,所以我想拥有5 browsers
。
我该怎么办? SynchronizationContext
是否已正确实施?