WPF等待UI完成

时间:2015-10-19 13:24:15

标签: wpf user-interface thread-safety

我有一个代码需要刷新UI然后等待它完成(刷新可能涉及动画)然后继续。有没有办法以同步的方式调用Application.Current.Dispatcher.Invoke(new Action (()=> { PerformUpdateWithAnimations(); }

这是整体外观:

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,但是在调用Application.Current.Dispatcher之后B blok“完成”,而不是在调度程序本身完成所有操作之后,它才能正常工作

如何让C等到B中的所有动画完成后?

1 个答案:

答案 0 :(得分:0)

您可以使用async / await来异步调用并在执行后继续...

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();
}