1

我希望加载指示器在方法执行之前立即启动。该方法的执行涉及实体框架的工作,因此我不(不能)将这种类型的代码放入新线程中,因为实体框架不是线程安全的。所以基本上在下面的方法中,我希望执行第一行并更新 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.

 }
4

2 回答 2

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();
}
于 2014-05-24T17:40:17.137 回答
0

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

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(); 
}
于 2014-05-23T17:22:52.147 回答