南希路线 - 回调时的返回值

时间:2016-09-01 11:55:27

标签: c# asynchronous event-handling .net-4.5 nancy

我有一个远程控制的应用程序。该程序必须根据请求播放动画,并在完成后响应客户端。这是我现在的代码(并且工作不正常):

public void PlayAnimation(Action callback)
{
    DoubleAnimation fadeOut = new DoubleAnimation
    {
        //settings
    };
    fadeOut.Completed += (s, e) => callback();
    BeginAnimation(OpacityProperty, fadeOut);
}


Get["/playAnim/{id}"] = param =>
{
    MainWindow.PlayAnimation(() => {/* Need to call "return" statement here */});
    return "Ok"; // This is where the value is returned now.
    //The execution gets here before animation was completed.
};

我知道,Nancy也支持async-await语法,但DoubleAnimation不支持(或者它支持?)。那么,在播放动画之后,如何让Nancy回复

1 个答案:

答案 0 :(得分:1)

正如您自己所说 - 南希支持异步方法,因此您可以使用TaskCompletionSource。代码的第二部分将如下所示:

Get["/playAnim/{id}"] = async param =>
{
    var completionSource = new TaskCompletionSource<bool>();
    MainWindow.PlayAnimation(() => { completionSource.SetResult(true); });

    await completionSource.Task;

    return "Ok"; 
};