简体   繁体   English

使用 Parallel.Foreach 更新具有线程安全性的实体的属性

[英]Use Parallel.Foreach to update properties of entity with thread safety

I am trying to leverage Parallel.Foreach to update properties of entity: Contact as shown in the code sample我正在尝试利用 Parallel.Foreach 来更新实体的属性:如代码示例中所示的联系人

var contactIds = new List<int>();
contactIds.AddRange(res.RelatedContacts.Select(c => c.IdVal).ToList());
contacts = await _dbContext.Contacts.Where(co => contactIds.Contains(co.ContactId)).ProjectTo<ContactDTO>(_mapper.ConfigurationProvider).AsNoTracking().ToListAsync();

foreach (var contactrec in contacts)
{
    var contact = contacts.FirstOrDefault(c => c.ContactId.Equals(contactrec.ContactId));
    if (contact != null)
    {
        contact.address = addresses.FirstOrDefault(a => a.AddressId.Equals(contact.AddressId));
        contact.ImagePath = contact.ImageId > 0 ? images.FirstOrDefault(im => im.ImageId.Equals(contact.ImageId)).FilePath : "NA";
    }
}

I want to replace the above code with Parallel.Foreach with thread safety.我想用具有线程安全性的 Parallel.Foreach 替换上面的代码。

I agree with the comments, there are some code smells there and probably writing the query in a more efficient way would speed up the whole process more than any optimization obtained with parallelism.我同意这些评论,那里有一些代码味道,并且可能以更有效的方式编写查询比通过并行获得的任何优化更能加快整个过程。

Having said this, I think that you're looking for something like this:话虽如此,我认为您正在寻找这样的东西:

var contactIds = new List<int>();
contactIds.AddRange(res.RelatedContacts.Select(c => c.IdVal).ToList());
contacts = await _dbContext.Contacts.Where(co => contactIds.Contains(co.ContactId)).ProjectTo<ContactDTO>(_mapper.ConfigurationProvider).AsNoTracking().ToListAsync();

Parallel.Foreach(contacts, contact => Update(contact));
//or: Parallel.Foreach(contacts, Update);
void Update(Contact contact){
    contact.address = addresses.FirstOrDefault(a => a.AddressId.Equals(contact.AddressId));
    contact.ImagePath = contact.ImageId > 0 ? images.FirstOrDefault(im => im.ImageId.Equals(contact.ImageId)).FilePath : "NA";
}

Some notes:一些注意事项:

  • no need to iterate through the Ids and then get the first element with that Id.无需遍历 Id,然后获取具有该 Id 的第一个元素。 Just iterate the elements.只需迭代元素。
  • there shouldn't be any thread safe issue, the operations in Update are readonly.不应该有任何线程安全问题, Update中的操作是只读的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM