Search code examples
c#multithreadingparallel-processingparallel.foreach

How can I convert foreach code to Parallel.ForEach?


I'm trying to read my zip faster to make my foreach loop parallel.

But how can i do that based on this method?

          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)
                {
                }
            }
        

How can i do this?

Thanks in advance!


Solution

  • I'm not sure what you're looking for, but here's how you can accomplish it based on your query. Keep in mind that your logic inside the foreach block must be "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));
    
                                }
                   });
    

    You can refer official documentation also - [1]:https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-write-a-simple-parallel-foreach-loop?redirectedfrom=MSDN