我有以下代码
var myResponse = new Response();
Parallel
.ForEach(itemsListDto
, new ParallelOptions { MaxDegreeOfParallelism = 10 }
, itemDto => {
var tResponse = _itemService
.InsertItem
(itemDto
, new RequestMessage
{UserName = RequestUserName});
myResponse.AddErrors(tResponse.Errors);
}
);
return myResponse;
myResponse 似乎没有添加所有的Errors。我应该如何重写它以确保安全?
请您参考如下方法:
您需要同步对 myResponse 的访问,因为这听起来像是 AddErrors 方法不是线程安全的:
var myResponse = new Response();
var syncObj = new object();
Parallel.ForEach(itemsListDto, new ParallelOptions { MaxDegreeOfParallelism = 10 }, itemDto =>
{
var tResponse = _itemService.InsertItem(itemDto, new RequestMessage {UserName = RequestUserName});
lock(syncObj)
myResponse.AddErrors(tResponse.Errors);
});
return myResponse;
如果 InsertItem 是一个相当长的过程,就性能而言这可能是可以接受的。
如果 InsertItem 是一个相当快的方法,这可能会增加很多同步开销,并导致整体时间接近同步循环。在这种情况下,您可能会使用 Parallel.ForEach which provide local state 的重载减少锁定频率,并将错误存储在本地状态中,然后在完整循环结束时聚合。我有一篇文章描述了 process required to aggregate data efficiently using Parallel.ForEach详细。
