为什么 BlobClient.UploadAsync 在通过内存流上传 JSON 时会挂起?



我正在尝试通过内存流将JSON上传到Azure blob。当我调用 UploadAsync 时,我的应用程序挂起。如果我将 UploadAsync 调用移到 StreamWriter 大括号之外,我会得到一个 System.ObjectDisposedException:"无法访问关闭的 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);
}
}

我使用了 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);
}

最新更新