C# EF LoadAsync后刷新视图
假设要加载大量数据,我希望UI在加载数据时能够响应。目前唯一有效的代码是以下代码,不断刷新不需要的UI。如何在非UI线程中加载数据并在视图中获得最终更新C# EF LoadAsync后刷新视图,c#,wpf,entity-framework,observablecollection,icollectionview,C#,Wpf,Entity Framework,Observablecollection,Icollectionview,假设要加载大量数据,我希望UI在加载数据时能够响应。目前唯一有效的代码是以下代码,不断刷新不需要的UI。如何在非UI线程中加载数据并在视图中获得最终更新 private static object sync_lock = new object(); private void Load() { MyEntities db = new MyEntities(); TestEntityViewModel testEntityViewModel = (TestEntityViewMo
private static object sync_lock = new object();
private void Load()
{
MyEntities db = new MyEntities();
TestEntityViewModel testEntityViewModel = (TestEntityViewModel)FindResource("testEntityViewModel");
testEntityViewModel.Source = db.TestEntities.Local; // Source is ObservableCollection<TestEntity>
BindingOperations.EnableCollectionSynchronization(testEntityViewModel.Source, sync_lock);
db.TestEntities.LoadAsync().ContinueWith(new Action<Task>(
(t) =>
{
this.Dispatcher.Invoke(new Action(() =>
{
View.MoveCurrentToFirst();
CommandManager.InvalidateRequerySuggested();
}));
}));
}
private static object sync_lock=new object();
专用空心荷载()
{
MyEntities db=新的MyEntities();
TestEntityViewModel TestEntityViewModel=(TestEntityViewModel)FindResource(“TestEntityViewModel”);
testEntityViewModel.Source=db.TestEntitys.Local;//源是ObservableCollection
BindingOperations.EnableCollectionSynchronization(testEntityViewModel.Source,同步锁定);
db.TestEntities.LoadAsync().ContinueWith(新操作(
(t) =>
{
this.Dispatcher.Invoke(新操作(()=>
{
View.MoveCurrentToFirst();
CommandManager.InvalidateRequestSuggested();
}));
}));
}
注意:如果我删除对
EnableCollectionSynchronization
的调用,则会加载数据,但ICollectionView
及其SourceCollection
只有一项。您似乎正在使用MVVM。这就是我在我的应用程序中的做法
interface ISomeDataService{
void GetModelItems(Action<Model[], Exception> callback);
}
class SomeDataServiceImpl:ISomeDataService{
void GetModelItems(Action<Model[], Exception> callback){
Task.Factory.StartNew(()=>{
//get model items from WCF for example than call the callback
//expected to take a while.
//you can also directly access DbContext from here
//if you like
callback(res, null);
});
}
}
此代码使用延迟加载。当UI控件读取Items属性时,将下载数据。在下载所有数据后,此代码将仅刷新集合一次。请注意,此示例适用于.NET4。如果您使用的是.NET4.5,则可以使用async/await关键字使服务更具可读性。但概念是一样的
class MyDemoVM{
private Model[] items;
private readonly ISomeDataService service;
private readonly IDispatcherService dispService;
public MyDemoVM(){
service=new SomeDataServiceImpl();
dispService=new DispatcherService();
//i use ctor injection here in order to break the dependency on SomeDataServiceImpl and on DispatcherService.
//DispatcherService delegates to the App dispatcher in order to run code
//on the UI thread.
}
public Model[] Items{
get{
if(items==null)GetItems();
return items;
}
set{
if(items==value)return;
items=value;
NotifyChanged("Items");
}
}
private void GetItems(){
service.GetModelItems((res,ex)=>{
//this is on a different thread so you need to synchronize
dispService.Dispatch(()=>{
Items=res;
});
});
}
}