2015-10-19 58 views
0

我有一個代碼需要刷新用戶界面,然後等待它完成(刷新可能涉及動畫),然後繼續。有沒有辦法以同步的方式撥打Application.Current.Dispatcher.Invoke(new Action (()=> { PerformUpdateWithAnimations(); }WPF等待用戶界面完成

這是整體外觀:

List<thingsThatMove> myThings = new List<ThingsThatMove>(); 

//normal code interacting with the data 
// let's name this part of code A 
foreach (thing t in myThings) 
{ 
    thing.currentPosition = SomePoint; 
    if(thing.wasRejectedBySystem) thing.needsToMove = true; 
} 



//As a result of A we have some impact in the UI 
//That may need some animations (let's call this bloc B) 
Application.Current.Dispatcher.Invoke(new Action(() => { 
    foreach(thing in myThings) 
     if(thing.needsToMove) 
       createNewAnimation(thing); 
})); 

//Here is some final code that needs the final position of some 
//of the elements, so it cannot be executed until the B part has 
// been finished. Let's call this bloc C 

updateInternalValues(myThings); 
cleanUp(); 

我試圖封裝B插入一個BackgroundWoker。設置B集團作爲DoWork和聽completed但doent工作,由於B BLOK「完成」的Application.Current.Dispatcher調用後,未調度後本身完成一切

我怎樣才能使C等待直到B中的所有動畫都完成了?

回答

0

您可以使用異步/等待到asynchrnously稱,它已經被執行後繼續..

private async void RefreshCode() 
{ 
    List<thingsThatMove> myThings = new List<ThingsThatMove>(); 

    //normal code interacting with the data 
    // let's name this part of code A 
    foreach (thing t in myThings) 
    { 
     thing.currentPosition = SomePoint; 
     if(thing.wasRejectedBySystem) thing.needsToMove = true; 
    } 

    //As a result of A we have some impact in the UI 
    //That may need some animations (let's call this bloc B) 
    await Application.Current.Dispatcher.InvokeAsync(new Action(() => { 
     foreach(thing in myThings) 
      if(thing.needsToMove) 
        createNewAnimation(thing); 
    })); 

    //Here is some final code that needs the final position of some 
    //of the elements, so it cannot be executed until the B part has 
    // been finished. Let's call this bloc C 

    updateInternalValues(myThings); 
    cleanUp(); 
} 
+0

如果Asyncrhonously開始代表......不會我的代碼一直下去,而不必等待它完成?我需要等待它完成之前繼續 – javirs

+0

是的..讓我更新一個新的答案。 –

+0

有沒有辦法將UI級別添加到任務?因爲在我的PerformUpdateWithAnimations裏有一個調用Application.dispatcher.invoke – javirs