c#之Webbrowser InvokeScript 函数阻塞 Windows Phone 8 中的 UI 线程
我正在 Windows Phone 8 中使用 Webbrowser 调用 Javascript 函数。
browserControl.InvokeScript(funtionName, args);
这个javascipt函数在内部调用一个服务来获取数据,在javascript调用期间我显示ProgressIndicator。
但我看不到 ProgressIndicator,因为 javascript 调用正在停止 UI 线程。
此问题可能是由于 Javascript 函数和我的 UI 线程在同一线程中运行所致。所以我尝试将我的 Javascript 函数调用移至后台线程,但失败并显示“无效的跨线程访问”
调用 ScriptNotify 后我能够看到 UI。在此之前我无法看到我的用户界面
您可以在下面看到我的代码片段:
有人可以建议我如何克服这个问题吗?
我的进度指示器代码:
public void ActivateProgressIndicator(this PhoneApplicationPage currentPage, string progressIndicatorText)
{
ProgressIndicator progressIndicator = new ProgressIndicator();
progressIndicator.Text = progressIndicatorText;
progressIndicator.IsVisible = true;
progressIndicator.IsIndeterminate = true;
SystemTray.SetProgressIndicator(currentPage, progressIndicator);
}
我的JS函数正在内部调用WCF休息服务,这个函数调用将花费30秒1分钟。我是后台线程的 JS 代码,如下所示:
ThreadPool.QueueUserWorkItem(o =>
{
WebBrowser browserControl = new WebBrowser();
browserControl.IsScriptEnabled = true;
browserControl.Navigate(new Uri("/WebAssets/Main.html", UriKind.RelativeOrAbsolute));
browserControl.InvokeScript("RetrieveAccounts",
"http://some.service.net/",
"Plain",
"arg1",
"arg2",
"arg3");
});
我在创建网络浏览器控件时收到无效的跨线程错误。
请您参考如下方法:
当调用java脚本方法时,通常也会显示此错误,该方法在网页内执行一些操作,例如异步调用。
就我而言,它有助于以这种方式调用方法:
我已采用 WB_LoadCompleted 事件来触发 invokescript 方法。您可以根据需要进行修改。
private void WB_LoadCompleted(object sender, NavigationEventArgs e)
{
// Make sure the HTML document has loaded before attempting to
// invoke script of the document page. You could set loadCompleted
// to true when the LoadCompleted event on the WebBrowser fires.
ActivateProgressIndicator(this, "hello");
Dispatcher.BeginInvoke(() =>
{
//Give a call to your Browser.InvokeScript here. e.g.
WB.InvokeScript("execScript", gestureHold);
});
}
希望这对您有帮助。 干杯
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。



