异步加载ImagePart数据错误

时间:2017-07-24 10:34:54

标签: asynchronous openxml docx

我使用DocumentFormat.OpenXml生成docx。我尝试从WebClient异步加载小png图像(20-50 kb)到我的docx。我对一个代码有不同的结果:

  • 没问题
  • 的NullReferenceException
  • FileFormatException
  • 的ObjectDisposedException
  • 出现InvalidOperationException

此代码演示了我的问题:

internal class Program
{
    public static void Main(string[] args)
    {
        using (var outputStream = new MemoryStream())
        {
            using (var doc = WordprocessingDocument.Create(outputStream, WordprocessingDocumentType.Document))
            {
                var mainPart = doc.AddMainDocumentPart();
                new Document(new Body()).Save(mainPart);
                var tasks = Directory.GetFiles("images").Select(async it =>
                    await AddImagePart(it, mainPart.AddImagePart(ImagePartType.Png)).ConfigureAwait(false));
                Task.WaitAll(tasks.ToArray());
            }
            File.WriteAllBytes("output.docx", outputStream.ToArray());
        }
    }

    private static async Task AddImagePart(string path, ImagePart imagePart)
    {
        using (var client = new WebClient())
        {
            var image = await client.DownloadDataTaskAsync(path).ConfigureAwait(false);
            imagePart.FeedData(new MemoryStream(image));
        }
    }

packages.config

<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="DocumentFormat.OpenXml" version="2.7.2" targetFramework="net46" />
<package id="System.IO.FileSystem.Primitives" version="4.0.1" targetFramework="net46" />
<package id="System.IO.Packaging" version="4.0.0" targetFramework="net46" />
</packages>

git大文件问题和.net少于4.6的问题。但我使用小文件和.net4.6。

1 个答案:

答案 0 :(得分:0)

也许您应该阅读this post关于异步\等待错误。

尝试制作ConfigureAwait(false)