如何将 foreach 代码转换为 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)
{
}
}
我该怎么做?
提前致谢!
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 = quot;{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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定您在寻找什么,但以下是您如何根据您的查询来完成它。请记住,foreach 块内的逻辑必须是“并行就绪”的。
您也可以参考官方文档 - [1]:https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-write-a-simple-parallel-foreach-loop?redirectedfrom=MSDN
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".
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