我有 DataGrid 的 WPF 项目。我使用 MVVM 模式。这是我的虚拟机的一部分:
class LibraryViewModel
{
#region Members
//private SimpleLibDBEntities _database;
ObservableCollection<BooksViewModel> _books = new ObservableCollection<BooksViewModel>();
int count = 0;
int sizeOfdb = 1000000;
#endregion
public ObservableCollection<BooksViewModel> Books
{
get
{
return _books;
}
set
{
_books = value;
}
}
public LibraryViewModel()
{
Task task = Task.Factory.StartNew(Generator);
}
private void Generator()
{
for (count = 0; count < sizeOfdb; count++)
{
_books.Add(new BooksViewModel { Book = new BooksSet { Id = count, Title = "Title"+count, Author = "Author", Publisher = "Publisher", Year = 1000, Note = "Note" } });
}
}
它有效,但我的 DataGrid 只显示了大约 50 000 -100 000 个元素(随机),而不是我的 int sizeOfdb = 1000000 个元素。为什么会这样?如何修复它?(没有“任务”一切正常)
在这个例子中我如何使用 async/await?类似的东西?(不工作。尝试使用 Dispathcher?)
public LibraryViewModel()
{
GeneratorAsync();
}
private async void GeneratorAsync()
{
await Task.Factory.StartNew(()=>{
for (count = 0; count < sizeOfdb; count++)
{
_books.Add(...);
}
});
}