我必须从数据库中读取 100.000 行,我使用以下代码:
List<elementClass> Listelement = new List<elementClass>();
using (DbDataReader reader = cmd.ExecuteReader())
{
while (reader .Read())
{
elementClass element= new elementClass();
DatabaseClass.ReadFromObject(reader , element);
Listelement.Add(element);
}
}
读取对象:
public static void ReadFromObject(DbDataReader dr, Object obj)
{
DataTable tableDescriptor = dr.GetSchemaTable();
try
{
//Id - Identifier
obj.GetType().GetProperty("Id").SetValue(obj, dr.GetValue(dr.GetOrdinal("Id")), null);
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach (PropertyInfo pi in properties)
{
if (!ExistColumn(tableDescriptor, pi.Name)) continue; // field not found
if (dr[pi.Name] == DBNull.Value) continue;
if (pi.PropertyType.IsEnum) { }
else
{
switch (pi.PropertyType.Name)
{
case "DateTime":
object dateValue = null;
if (dr[pi.Name].GetType().Name == "String")
dateValue = F24Common.Utility.DateFromString(dr.GetString(dr.GetOrdinal(pi.Name)));
else
dateValue = dr.GetDateTime(dr.GetOrdinal(pi.Name));
pi.SetValue(obj, dateValue, null);
break;
default:
pi.SetValue(obj, dr.GetValue(dr.GetOrdinal(pi.Name)), null);
break;
}
}
}
}
catch (Exception )
{
}
}
这段代码肯定有问题,太慢了(整个处理过程需要 45-50 分钟)。是否可以同时使用多个 CPU 内核(我有一个四核 CPU)来填充列表?