【问题标题】:Parallel.foreach - Downloading images from Active Directory and saving it to folder. Is it thread safeParallel.foreach - 从 Active Directory 下载图像并将其保存到文件夹。它是线程安全的吗
【发布时间】:2016-08-23 14:28:19
【问题描述】:

我有一个方法:GetThumbnailPhotoForProfile(),我将 list<EmployeeInfo> 传递给该方法,该方法几乎没有 FirstName、LastName 和 EmailAddress 等属性。在该方法中,我使用以下代码,该代码基于每个电子邮件地址连接到 Active Directory 并获取配置文件图像并将其保存到一个位置 (C:\Temp:\Images)

private bool GetThumbnailPhotoForProfile(List<EmployeeInfo> EmployeeInfoList)
{

Parallel.ForEach(employeeInfoList.Select(emp=>emp.EmailAddress).ToList(),emailAddress =>
{
  var thumbnail = emailAddress.GetThumbnailPhoto();

  if (thumbnail != null)
  {
    thumbnail.Save("C:\Test\Images\" + emailAddress + ".jpg", ImageFormat.Jpeg);
  }
  else
  {
    Log.Information("Thumbnail photo is not available for the {EmailAddress}.", emailAddress);
  }  

});

}

我最初使用 foreach 循环并发现该方法花费的时间更多,然后我更新代码以使用 Parallel.ForEach 并发现它花费的时间更少。我测试了很多次,发现同样的性能差异。 这里想知道上面的方法是线程安全高效还是有更好的实现方式。

谁能在这里指导我。

【问题讨论】:

  • Parallel 结构肯定会将线性 for 循环变成多线程 for 循环,因此它必须是线程安全的?
  • 您发现上面的代码有什么问题吗?我想知道它是线程安全的。

标签: c# c#-4.0 parallel.foreach


【解决方案1】:

仅根据您显示的代码无法回答代码是否是线程安全的问题。这取决于 GetThumbnailPhoto()Save() 究竟做了什么,可能还取决于 EmployeeInfoList 的构造方式。

【讨论】:

  • EmployeeInfoList:这是一个 EmployeeInfo 类的列表,其中包含我从数据库中获取的 Employeeinfo。我将该列表传递给 GetThumbnailPhotoForProfile,后者又调用另一个扩展方法:GetThumbnailPhoto(),我在其中连接到 AD 并获取每个配置文件的 thmbnailphoto,然后将其保存到文件系统
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-26
  • 1970-01-01
  • 2019-11-18
  • 2013-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多