0

대량의 데이터를로드한다고 가정 할 때 데이터를로드하는 동안 UI가 응답해야합니다. 현재 유일한 작업 코드는 다음과 같습니다. 항상은 원하지 않는 UI를 새로 고칩니다. UI가 아닌 스레드에서 데이터를로드하고 최종 업데이트를 얻는 방법은 무엇입니까?EF LoadAsync 후의 화면 새로 고침

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(); 
        })); 
       })); 
} 

참고 : 나는 EnableCollectionSynchronization에 전화를 제거하면 데이터가로드하지만 ICollectionViewSourceCollection 것이다 단 1 항목입니다.

답변

1

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); 
     }); 
    } 
} 

이제 VM에서이 구현을 사용해야합니다. 당신은 아래와 같이 이것을 할 수 있습니다.

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; 
      }); 
     }); 
    } 
} 

이 코드는 지연로드를 사용합니다. UI 컨트롤이 Items 속성을 읽을 때 데이터가 다운로드됩니다. 이 코드는 모든 데이터가 다운로드 된 후 컬렉션을 한 번만 새로 고칩니다. 이 예제는 .net 4에 유용합니다. .net 4.5를 사용하는 경우 async/await 키워드를 사용하여 서비스를보다 쉽게 ​​읽을 수 있습니다. 개념은 동일합니다.