You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF中同时加载20+BitmapImage时部分下载卡住的问题求助

WPF多Image控件批量下载图片时部分加载卡住的解决方案
  • 调整HTTP并发连接数
    .NET默认的ServicePointManager.DefaultConnectionLimit值较低(默认2),当同时发起20+下载请求时,大部分请求会处于排队等待状态,超时后就会卡住。在App启动时(比如App.xaml.cs的OnStartup方法)设置更高的并发数:

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        ServicePointManager.DefaultConnectionLimit = 50; // 根据实际需求调整
    }
    
  • 改用后台线程手动下载图片流
    直接通过BitmapImage.UriSource加载,底层下载逻辑无法精准控制,改用HttpClient在后台线程下载流后再绑定到BitmapImage,能更稳定处理批量加载场景:
    修改Converter代码如下:

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var uriStr = value as string;
        if (string.IsNullOrEmpty(uriStr)) return null;
    
        var bitmap = new BitmapImage();
    
        _ = Task.Run(async () =>
        {
            try
            {
                using var httpClient = new HttpClient();
                using var stream = await httpClient.GetStreamAsync(uriStr);
    
                Application.Current.Dispatcher.Invoke(() =>
                {
                    bitmap.BeginInit();
                    bitmap.CacheOption = BitmapCacheOption.OnLoad;
                    bitmap.StreamSource = stream;
                    bitmap.EndInit();
                    bitmap.Freeze(); // 冻结后可安全跨线程访问,提升性能
                });
            }
            catch (Exception ex)
            {
                // 处理下载失败逻辑,比如显示占位图
                Application.Current.Dispatcher.Invoke(() =>
                {
                    bitmap.UriSource = new Uri("pack://application:,,,/Assets/Placeholder.png");
                });
            }
        });
    
        return bitmap;
    }
    
  • 移除不必要的缓存忽略设置
    原代码中BitmapCreateOptions.IgnoreImageCache会强制每次重新下载图片,增加并发压力和带宽消耗。如果没有特殊需求,建议移除该设置,让系统自动缓存已下载的图片,减少重复请求。

  • 添加下载失败重试机制
    对于偶尔下载失败的情况,可以在HttpClient请求时添加重试逻辑——比如手动实现简单的重试循环,或者使用重试库(如Polly),提升批量加载的成功率。

内容的提问来源于stack exchange,提问作者Yelo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 11:27:19