【发布时间】:2021-06-12 15:11:41
【问题描述】:
我是发送到 api 的对象列表。我在下面使用了并行线程。
代码
List<object> data ;//contain data
result =new Dictionary<decimal, object>();
var threadCount = 4;
if (data.Count < threadCount)
{
threadCount = data.Count;
}
var pageSize = threadCount > 0 ? Convert.ToInt32(Math.Ceiling((Convert.ToDecimal(data.Count) / threadCount))) : 0;
var pageCount = threadCount;
for (int j = 0; j < threadCount; j++)
{
var temp = data.Skip(j * pageSize).Take(pageSize).ToList();
var tempLength = temp?.Count;
Parallel.ForEach(temp, item =>
{
result.Add(item.ID, null);
//call Api and get resultApi
if (resultApi != null && resultApi.Result != null)
{
result[item.ID] = resultApi.Result.id;
}
else if (resultApi != null && resultApi .Message != null)
{
result[item.ID] = null;
}
else
{
result[item.ID] = null;
}
});
}
问题
在检查结果的顶部操作中,我看到一些项目与其 ID 无关并且已被移动。如果退出并行模式时没有移位,则所有标识符都设置正确
如何解决问题?
【问题讨论】:
-
从哪里开始。
Dictionary不是线程安全的。因此,您需要将其更改为线程安全的数据结构(ConcurrentDictionary似乎很合适)。也就是说,您如何使用该数据结构也需要是线程安全的,但也不是。最好先确定要在本地输入字典的内容,然后在最后的 1 个操作中将其写入ConcurrentDictionary。很难说虽然不知道到底发生了什么以及你想要实现什么 -
@Knoop 非常感谢。我想在操作结束时将对象列表作为批量存储在数据库中
-
//call Api and get resultApi-> 这是异步调用吗? -
@JohnathanBarclay ,非常感谢,是的。
标签: c# multithreading parallel-processing parallel.foreach