如何将 foreach 代码转换为 Parallel.ForEach?

How can I convert foreach code to Parallel.ForEach?

我正在尝试更快地读取 zip 以使我的 foreach 循环并行。

但是根据这个方法我该怎么做呢?

          private async Task GetImage()
            {
                try
                {
                    PathToZip();
                    int currentIndex = GetCurrentIndex();
                    Content content = _protocol.contents[currentIndex];
                    string imageName = $"{content.contentid}.jpg";

                    using (ZipArchive archive = ZipFile.OpenRead(PathToZip()))
                    {
                        foreach (ZipArchiveEntry pictureEntry in archive.Entries)

                        {
                            if (string.Equals(pictureEntry.Name, imageName, StringComparison.OrdinalIgnoreCase))
                            {
                                //for reading the image
                                byte[] buffer;
                                long length = pictureEntry.Length;
                                buffer = new byte[length];
                                pictureEntry.Open().Read(buffer, 0, (int)length);
                                myImage.Source = ImageSource.FromStream(() => new MemoryStream(buffer));

                            }
                        }
                    }


                }
                catch (Exception)
                {
                }
            }
        

我该怎么做?

提前致谢!

我不确定您要查找什么,但可以根据您的查询按以下方式完成查找。请记住,foreach 块内的逻辑必须是“paralleled-ready”。

Paraller.foreach (archive.Entries,(pictureEntry)=>
               {
                            if (string.Equals(pictureEntry.Name, imageName, StringComparison.OrdinalIgnoreCase))
                            {
                                //for reading the image
                                byte[] buffer;
                                long length = pictureEntry.Length;
                                buffer = new byte[length];
                                pictureEntry.Open().Read(buffer, 0, (int)length);
                                myImage.Source = ImageSource.FromStream(() => new MemoryStream(buffer));

                            }
               });

您也可以参考官方文档 - [1]:https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-write-a-simple-parallel-foreach-loop?redirectedfrom=MSDN