[英]How to Invoke or BeginInvoke Control from another thread
from the class I am calling thread
with 从类我打电话
thread
与
using (GeckoBrowserForm geckoBrowserForm = new GeckoBrowserForm(XulRunnerPath, propertyBag.ResponseUri.ToString()))
{
geckoBrowserForm.show();
}
that execute UI form OnLoad(EventArgs e)
执行UI形式的
OnLoad(EventArgs e)
protected override void OnLoad(EventArgs e)
{
GeckoWebBrowser m_GeckoWebBrowser = new GeckoWebBrowser();
m_GeckoWebBrowser.Invoke(new Action(() => {
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;
}
if (m_Url.Equals(m_GeckoWebBrowser.Document.Url.ToString(), StringComparison.OrdinalIgnoreCase))
{
Done = true;
//m_GeckoWebBrowser.Navigate("about:blank");
//m_GeckoWebBrowser.Document.Cookie = "";
//m_GeckoWebBrowser.Stop();
}
};
m_GeckoWebBrowser.Navigate(m_Url);
}));
}
but problem is that code inside Invoke is never executed. 但是问题是Invoke内部的代码从未执行过。 Why?
为什么? How can i execute code inside invoke?
我如何在内部执行代码?
Problem is that GeckoBrowser is a Windows Forms Control. 问题是GeckoBrowser是Windows窗体控件。 A Control's properties and methods may be called only from the thread on which the Control was created.
只能从创建控件的线程中调用控件的属性和方法。 To do anything with a Control from another thread, you need to use the Invoke or BeginInvoke method, eg but how?
要使用另一个线程的Control做任何事情,您需要使用Invoke或BeginInvoke方法,例如,但是如何?
OnLoad
is called on the UI-thread, therefore invoking is not necessary. 在UI线程上调用了
OnLoad
,因此不需要调用。 Besides that, you could also call these initialization steps in the constructor of the class. 除此之外,您还可以在类的构造函数中调用这些初始化步骤。
Update : To create it with a SynchronizationContext: 更新 :要使用SynchronizationContext创建它:
void ThreadFunc(object args)
{
...
var syncContext = (SynchronizationContext) args;
syncContext.Send(new SendOrPostCallback(_ => {
using (GeckoBrowserForm geckoBrowserForm = new GeckoBrowserForm(XulRunnerPath, propertyBag.ResponseUri.ToString()))
{
geckoBrowserForm.ShowDialog();
}),
null);
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.