C# 并行复制 - 小文件问题

标签 c# azure azure-functions

我有一个 C# Azure 函数,用于从 Blob 读取文件内容并将其写入 Azure Data Lake 目标。该代码对于大尺寸文件(~8 MB 及以上)工作得非常好,但对于小尺寸文件,目标文件写入 0 字节。我尝试将 block 大小更改为较小的数字,并将并行线程更改为 1,但行为保持不变。我正在模拟 Visual Studio 2017 中的代码。

请找到我正在使用的代码片段。我已经阅读了有关 Parallel.ForEach 限制的文档,但没有遇到任何与文件大小问题有关的具体内容。 (https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/potential-pitfalls-in-data-and-task-parallelism)

        int bufferLength = 1 * 1024 * 1024;//1 MB chunk
        long blobRemainingLength = blob.Properties.Length;
        var outPutStream = new MemoryStream();
        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;
        }
        Console.WriteLine("Number of Queues: " + queues.Count);

        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).GetAwaiter().GetResult();
                      lock (mystream)
                        {

                          var bytes = ms.ToArray();
                          Console.WriteLine("Processing on thread {0}", 
                           Thread.CurrentThread.ManagedThreadId);
                           mystream.Write(bytes, 0, bytes.Length);

                        }

                }
             });

感谢所有的帮助!!

最佳答案

我发现我的代码存在问题。 ADL Stream writer 未正确刷新和处置。添加必要的代码后,小/大文件的并行化工作正常。

感谢您的建议!!

关于C# 并行复制 - 小文件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50821028/

相关文章:

azure - 在 VSCode 中调试 Azure Function (Python) 和 RuntimeError : Can't listen for client connections: [WinError 10048]

c# - 使用切换按钮停止协程

c# - 在 try/finally 外部或内部初始化一次性资源

azure - 如何在 AKS NginX Ingress 中公开服务

azure - 使用 Rest API 在 Azure Devops 中创建工作项时出错

azure - 如何从 Azure 登录到外部程序?

c# - 按索引获取 PerformanceCounter

c# - 为什么这个时区更正夏令时

http - Bing API 请求的 Ajax 授权 header 是什么?

azure-functions - Azure Functions、Servicebus 和 CorrelationId 的一致方法是什么?