【问题标题】:UWP application hangs when using multiple Webviews with heavy URLs使用具有大量 URL 的多个 Web 视图时,UWP 应用程序挂起
【发布时间】:2020-06-09 03:45:59
【问题描述】:

我必须在 URL 之间轮换(比如说 10 个 URL)。每个 url 都有自己的 Webview,每个 webview 显示 15 秒(一次一个)。我可以从服务器更改 url,然后立即显示到 UWP 应用程序上。

如果互联网中断,WebViews 仍应在间隔之后在所有 url 之间旋转,这就是我们使用多个 webviews 的原因。

目前的情况是,我更改的 URL 越多,占用的 RAM 就越多,最终会挂起。

【问题讨论】:

    标签: c# uwp


    【解决方案1】:

    WebViews是重量级控件,请不要创建多个实例来渲染html页面,对于这种情况,您可以使用定时器每15s更改一个mvvm模式的webview源。即使互联网断了,它仍然可以工作。请检查以下代码。

    public sealed partial class MainPage : Page, INotifyPropertyChanged
    {
        public MainPage()
        {
            this.InitializeComponent();
            initUri();
            var timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(15);
            timer.Tick += Timer_Tick;
            timer.Start();
            Source = new Uri("xxxxxx");
    
        }
        private List<Uri> _uris = new List<Uri>();
        private void initUri()
        {
    
            _uris.Add(new Uri("xxxxxx"));
            _uris.Add(new Uri("xxxxxx"));
            _uris.Add(new Uri("xxxxxx"));       
    
        }
    
        int count = 0;
        private void Timer_Tick(object sender, object e)
        {
    
            Source = _uris[count];
            count++;
            if (count == _uris.Count)
            {
                count = 0;
            }
        }
    
    
    
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        private Uri _source;
        public Uri Source
        {
            get
            {
                return _source;
            }
    
            set
            {
                _source = value;
                OnPropertyChanged();
            }
        }
    }
    

    Xaml

    <WebView
        x:Name="MyWebView"
        HorizontalAlignment="Stretch"
        VerticalAlignment="Stretch"
        Source="{x:Bind Source, Mode=OneWay}"
        />
    

    【讨论】:

    • 感谢您的回答。我在这里有一个问题,当我们没有互联网时,如何在计时器回调中加载新的源 URI。我们如何缓存它们?互联网不再可用后,我必须在 Uris 之间继续旋转。
    • 在断网期间,定时器仍然工作,它会加载url,但不会得到响应,如果15s内没有恢复internet,webview会加载下一个,直到网络简历
    猜你喜欢
    • 2020-03-02
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 2013-04-17
    相关资源
    最近更新 更多