南希路由-回调时返回值

本文关键字:返回值 回调 路由 | 更新日期: 2023-09-27 18:05:04

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

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响应呢?

南希路由-回调时返回值

正如你自己所说- Nancy支持async方法,所以这里你可以使用TaskCompletionSource。代码的第二部分看起来像这样:

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