【问题标题】:Why does BlobClient.UploadAsync hang when uploading JSON via a memory stream?为什么通过内存流上传 JSON 时 BlobClient.UploadAsync 会挂起?
【发布时间】:2020-10-09 17:53:13
【问题描述】:

我正在尝试通过内存流将 JSON 上传到 Azure blob。当我调用 UploadAsync 我的应用程序挂起。如果我将 UploadAsync 调用移到 StreamWriter 大括号之外,我会得到一个 System.ObjectDisposedException: 'Cannot access a closed Stream。'例外。如何将 JSON 流式传输到 blob?

            var blobClient = new BlobClient(new Uri(storageUri), options);

            var serializer = JsonSerializer.Create(this.serializerSettings);

            using (var stream = new MemoryStream())
            {
                using (var writer = new StreamWriter(stream))
                {
                    serializer.Serialize(writer, job);

                    await blobClient.UploadAsync(stream, overwrite: true, cancellationToken: cancellationToken);
                }
            }

【问题讨论】:

标签: azure json.net blob azure-blob-storage memorystream


【解决方案1】:

我使用 leaveOpen 选项来保持内存流打开。在上传到 blob 之前,我还重绕了内存流。

            var blobClient = new BlobClient(new Uri(storageUri), options);

            var serializer = JsonSerializer.Create(this.serializerSettings);

            using (var stream = new MemoryStream())
            {
                // Use the 'leave open' option to keep the memory stream open after the stream writer is disposed
                using (var writer = new StreamWriter(stream, Encoding.UTF8, 1024, true))
                {
                    // Serialize the job to the StreamWriter
                    serializer.Serialize(writer, job);
                }

                // Rewind the stream to the beginning
                stream.Position = 0;

                // Upload the job via the stream
                await blobClient.UploadAsync(stream, overwrite: true, cancellationToken: cancellationToken);
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 2012-02-17
    • 2022-01-20
    • 2017-09-19
    • 2016-05-06
    • 1970-01-01
    • 2015-05-15
    相关资源
    最近更新 更多