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

.NET 9 MAUI安卓应用使用PdfSharpCore加载图片时冻结问题

解决.NET 9 MAUI Android应用中PdfSharpCore加载图片导致的冻结问题

问题根源

XImage.FromFile是同步IO操作,在Android平台直接读取FileSystem.AppDataDirectory下的图片文件时,同步阻塞会占用UI线程,导致应用出现冻结卡顿,尤其在图片数量多、体积大时更明显。

修复方案

通过异步IO读取图片流、异步执行图片添加逻辑,避免阻塞UI线程:

  1. 重构图片加载逻辑为异步流读取
    替换同步的FromFile,改用异步读取文件流后通过XImage.FromStream加载图片,同时用using确保资源正确释放。

  2. 将图片添加方法改为异步
    把原同步的AddImages改为异步方法,调用时使用await保证整个PDF生成流程不会阻塞UI。

修改后的代码示例

异步图片添加方法

private async Task AddImagesAsync(PdfSharpCore.Pdf.PdfDocument pdfDocument, List<Photo> photos)
{
    try
    {
        foreach (var photo in photos)
        {
            if (File.Exists(photo.FilePath))
            {
                PdfPage page = pdfDocument.AddPage();
                using (XGraphics xGr = XGraphics.FromPdfPage(page))
                {
                    // 异步打开文件流,避免同步IO阻塞UI
                    using (var fileStream = new FileStream(
                        photo.FilePath, 
                        FileMode.Open, 
                        FileAccess.Read, 
                        FileShare.Read, 
                        bufferSize: 4096, 
                        useAsync: true))
                    {
                        // 从流加载图片
                        var image = XImage.FromStream(() => fileStream);
                        xGr.DrawImage(image, 10, 10, image.PixelWidth, image.PixelHeight);
                    }
                }
            }
        }
    }
    catch (Exception e)
    {
        throw;
    }
}

异步报表生成方法

public async Task<byte[]> EntryExitReport(EntryExitReport i)
{
    try
    {
        using (PdfDocument document = new PdfDocument())
        {
            PdfPage page = document.AddPage();
            GenerateTableEntry(page, i);
            if(i.Photos?.Count > 0)
            {
                // 等待异步图片添加完成
                await AddImagesAsync(document, i.Photos.ToList());
            }
            using (MemoryStream stream = new MemoryStream())
            {
                document.Save(stream);
                return stream.ToArray();
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"生成报表时出错: {ex.Message}");
        return null;
    }
}

额外优化建议

  • 图片压缩预处理:对高分辨率图片先进行压缩,减少IO读取时间和内存占用,可借助MAUI的图片处理API或第三方库实现。
  • 后台线程执行:若报表生成逻辑复杂,可将整个生成任务放到后台线程(如await Task.Run(() => EntryExitReport(i))),进一步避免UI线程阻塞。
  • 路径校验:确保photo.FilePath是Android平台有效的文件路径,路径格式错误可能导致IO异常或阻塞。

内容的提问来源于stack exchange,提问作者Steven Gazo M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 05:07:32