问题描述
我有一个 foreach 循环可以多次调用 _webView.NavigateToLocalStreamUri(url[index], resolver)
.据我所知,每次导航到特定 URL 时,都会触发事件 NavigationStarting
和 NavigationCompleted
.但就我而言,NavigationStarting
会为每个请求调用,但 NavigationCompleted
仅在最后一个请求时触发.我想知道有没有办法确保为每个请求调用 NavigationCompleted
.我搜索了但没有符合我目的的答案.
I have a foreach loop to call _webView.NavigateToLocalStreamUri(url[index], resolver)
many times. As I know each time I navigate to a specific URL, the events NavigationStarting
and NavigationCompleted
are triggered. But in my case, NavigationStarting
is called for every request but NavigationCompleted
only trigger for the last request. I want to know Is there a way to make sure NavigationCompleted
is called for every request. I searched but there is no answer meet my purpose.
for (int i = 0; i < 3; i++){
// here I raise event to call `NavigateToLocalStreamUri` of _webview
}
_webview 有 2 个事件 NavigationStarting
和 NavigationCompleted
_webview have 2 events NavigationStarting
and NavigationCompleted
//当 i = 0 or 1
程序只调用NavigationStarting
的事件处理程序,不调用NavigationCompleted
// when i = 0 or 1
the program only calls event handler of NavigationStarting
, but not call event handler of NavigationCompleted
//当i = 2
(总是for
循环的最后一次迭代)程序调用 NavigationStarting
和 NavigationCompleted
// when i = 2
(always, the last iteration of for
loop)the program calls event handler of both events NavigationStarting
and NavigationCompleted
//有没有办法确保当 i = 0 或 1 时,NavigationCompleted
处理程序被调用?
// Is there any solution to make sure when i = 0 or 1, NavigationCompleted
handler is called?
推荐答案
我复制了您的问题.该问题是由 for
循环在上一个导航完成之前继续引起的.
I reproduced your issue. The issue is caused by the for
loop continue before the previous navigation completed.
解决这个问题的关键是等待前面的 NavigationCompleted
事件句柄发生.你可以使用 AutoResetEvent
通知等待线程发生了事件.例如:
The key point to resolve this is to wait for the previous NavigationCompleted
event handle occurred.You could use AutoResetEvent
which notifies a waiting thread that an event has occurred. For example:
public MainPage()
{
this.InitializeComponent();
urls = new List<Uri>();
waitForNavComplete = new AutoResetEvent(false);
urls.Add(...);
}
List<Uri> urls;
AutoResetEvent waitForNavComplete;
private async void btnnavigate_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 3; i++)
{
mywebview.Navigate(urls[i]);
await Task.Run(() => { waitForNavComplete.WaitOne(); });
}
}
private void mywebview_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
System.Diagnostics.Debug.WriteLine(args.Uri.ToString());
waitForNavComplete.Set();
}
使用 Set
方法将完成事件的状态设置为已发出信号,以便 for
循环将停止等待并继续.
Using Set
method to set the state of the completed event to signaled so that for
loop will stop waiting and continue.
这篇关于UWP Webview 只为最后一次请求触发 NavigationCompleted 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!