2015-10-19 68 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