我有一个存储库类,称调用FileRepository()在C#托管层中工作。有一个方法调用LoadRecordFromFile(),它访问C ++非托管COM DLL以加载大量记录,如图所示:
LoadRecordFromFile()
{
for (uint index = 1; index <= this.File.Count; index++)
{
// create new record object here
}
}
记录对象中的信息稍后将用于生成AnalysisViewModel对象。因此,还有另一个for循环用于生成AnalysisViewModel对象的集合,然后才能在View中显示它。
问题是第二个for循环使用了大量的加载时间。我试图通过在LoadRecordFromFile()中使用一个for循环替换两个for循环来优化加载时间。即在FileRepository类的LoadRecordFromFile()中的for循环中一起创建记录对象和AnalysisViewModel()对象。然而,它打破了存储库设计模式的封装。 请有人建议如何重新设计这两个类(AnalysisVeiwModel和FileRepository)以实现只使用一个for循环来减少文件加载时间?谢谢
答案 0 :(得分:1)
我会在视图模型中存储一组记录,而不只是一个。
所以你可以有AnalysisRecordsViewModel
一次从存储库中获取所有记录。
如果要在视图中显示或编辑单个记录,可以使用第二个视图模型(如AnalysisViewModel
)来显示单个记录。
答案 1 :(得分:1)
创建一个自定义枚举器,将API调用包装到COM dll中。
首先声明您的收藏。该集合只是一个创建枚举器的包装器:
public class MyCustomCollection : IEnumerable<YouRecordType>
{
private readonly string _fileName;
public MyCustomCollection(string fileName)
{
if (fileName == null) throw new ArgumentNullException(nameof(fileName));
_fileName = fileName;
}
public IEnumerator<YouRecordType> GetEnumerator()
{
return new MyCustomEnumerator(_fileName);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
..您的存储库应该返回该集合。
枚举器本身是使用COM对象的类:
public class MyCustomEnumerator : IEnumerator<YouRecordType>
{
private readonly string _fileName;
private int _index;
YouRecordType _current;
public MyCustomEnumerator(string fileName)
{
_fileName = fileName;
//open COM object here
}
public void Dispose()
{
//Dispose used COM resources.
}
public bool MoveNext()
{
//Read next row from the COM object
var couldReadAnotherRow = true;
_current = null; //comObject.Read(_index++);
return couldReadAnotherRow;
}
public void Reset()
{
//want to start over
}
public YouRecordType Current { get { return _current; } }
object IEnumerator.Current
{
get { return Current; }
}
}
您可以将其视为延迟加载的集合。即在被调用之前不会加载任何行。
因此,从存储库中返回该对象应该没有时间。而且你不必从头开始预装所有东西。
可枚举的工作方式与其他任何集合一样。您可以使用yourCollection.ToList()
加载所有行,或foreach(var yourType in yourCollection)
在每次迭代中加载新行。