簡體   English   中英

在實際執行方法之前更新UI

[英]Update UI before actual execution of method

我希望加載指示器在方法執行之前立即開始。 該方法的執行涉及實體框架的工作,因此我不(不能)將這種類型的代碼放入新的線程中。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.

 }

您可以在UI調度程序上調用優先級設置為Render的空委托 ,以便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(); 
}

假設繁忙的指示器可見性已綁定到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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM