在实际执行方法之前更新UI

时间:2014-05-23 16:12:31

标签: c# wpf entity-framework busyindicator

我希望在执行方法之前立即启动加载指示器。该方法的执行涉及实体框架的工作,所以我不(不能)将该类型的代码放在新的线程中,bc实体框架不是线程安全的。所以基本上在下面的方法中,我希望第一行执行并进行UI更新,然后返回并执行其余的代码。有什么想法吗?

 public async void LoadWizard()
 {
    IsLoading = true; //Need the UI to update immediately 

    //Now lets run the rest (This may take a couple seconds)
    StartWizard();
    Refresh(); 
 }

我不能这样做:

 public async void LoadWizard()
 {
    IsLoading = true; //Need the UI to update immediately 

    await Task.Factory.StartNew(() =>
    {
        //Now lets run the rest (This may take a couple seconds)
        StartWizard();
        Refresh(); //Load from entityframework
    });

    //This isn't good to do entityframework in another thread. It breaks.

 }

2 个答案:

答案 0 :(得分:0)

您可以在UI调度程序上调用空委托,优先级设置为Render ,以便UI处理所有排队操作的优先级等于或高于Render。 (UI重绘Render调度程序优先级)

public async void LoadWizard()
{
   IsLoading = true; //Need the UI to update immediately 

   App.Current.Dispatcher.Invoke((Action)(() => { }), DispatcherPriority.Render);

   //Now lets run the rest (This may take a couple seconds)
   StartWizard();
   Refresh(); 
}

答案 1 :(得分:0)

假设繁忙的指标可见​​性绑定到IsLoading属性,则在StartWizard或Refresh方法中出现“错误”。您的StartWizard和Refresh方法应仅加载数据源中的数据。您必须没有任何代码可以更改加载方法中的UI状态。这是一些伪代码..

public async void LoadWizard()
 {
    IsLoading = true; 

    StartWizard();
    var efData = Refresh(); 

    IsLoading = false;

    //update values of properties bound to the view
    PropertyBoundToView1 = efData.Prop1;
    PropertyBoundToView2 = efData.Prop2;
 }

public void StartWizard()
{
  //do something with data that are not bound to the view
}

public MyData Refresh()
{
   return context.Set<MyData>().FirstOrDefault();
}