簡體   English   中英

C#:從 ADLS gen2 blob 下載大型 json 文件並反序列化為對象

[英]C#: Download large sized json file from ADLS gen2 blob and Deserialize to object

我正在使用以下代碼將數據從 blob 輸出到流:

    private static async Task<Stream> ParallelDownloadBlobAsync(Stream outPutStream, CloudBlockBlob blob)
    {

        await blob.FetchAttributesAsync();
        int bufferLength = 1 * 1024 * 1024;//1 MB chunk
        long blobRemainingLength = blob.Properties.Length;
        Queue<KeyValuePair<long, long>> queues = new Queue<KeyValuePair<long, long>>();
        long offset = 0;
        while (blobRemainingLength > 0)
        {
            long chunkLength = (long)Math.Min(bufferLength, blobRemainingLength);
            queues.Enqueue(new KeyValuePair<long, long>(offset, chunkLength));
            offset += chunkLength;
            blobRemainingLength -= chunkLength;
        }
        Parallel.ForEach(queues, new ParallelOptions()
        {
            //Gets or sets the maximum number of concurrent tasks
            MaxDegreeOfParallelism = 10
        }, (queue) =>
        {
            using (var ms = new MemoryStream())
            {
                blob.DownloadRangeToStreamAsync(ms, queue.Key, queue.Value);
                lock (outPutStream)
                {
                    outPutStream.Position = queue.Key;
                    var bytes = ms.ToArray();
                    outPutStream.Write(bytes, 0, bytes.Length);
                }
            }
        });

        return outPutStream;
    }

然后我使用 JsonSerializer 來反序列化數據但是塊沒有執行

 await ParallelDownloadBlobAsync(stream, cloudBlockBlob);

                //resetting stream's position to 0

                //stream.Position = 0;
                var serializer = new JsonSerializer();

                    using (var sr = new StreamReader(stream))
                    {
                        using (var jsonTextReader = new JsonTextReader(sr))
                        {
                            jsonTextReader.SupportMultipleContent = true;
                            result = new List<T>();


                            while (jsonTextReader.Read())
                            {
                                result.Add(serializer.Deserialize<T>(jsonTextReader));
                            }

                        }
                    }

如果我使用DownloadToStreamAsync而不是並行下載( DownloadRangeToStreamAsync ),那么它可以工作。

我可以重現您的問題,這里的解決方案是在ParallelDownloadBlobAsync方法中,更改這行代碼blob.DownloadRangeToStreamAsync(ms, queue.Key, queue.Value); blob.DownloadRangeToStream(ms, queue.Key, queue.Value);

不確定您和我的問題的根本原因是否相同。 在我這邊,根本原因是當文件很小(比如 100kb)時,使用blob.DownloadRangeToStreamAsync方法時,輸出流始終為 0,因此永遠不會執行while condition 但是對於較大的文件,可以使用blob.DownloadRangeToStreamAsync方法。

如果無法解決您的問題,請發表評論。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM