Nancy 路由 - return 回调值
Nancy route - return value on callback
我有一个远程控制的应用程序。该程序必须根据请求播放动画,并在完成时响应客户端。这是我现在的代码(它不能正常工作):
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 支持异步方法,因此您可以在此处使用 TaskCompletionSource。您的代码的第二部分将如下所示:
Get["/playAnim/{id}"] = async param =>
{
var completionSource = new TaskCompletionSource<bool>();
MainWindow.PlayAnimation(() => { completionSource.SetResult(true); });
await completionSource.Task;
return "Ok";
};
我有一个远程控制的应用程序。该程序必须根据请求播放动画,并在完成时响应客户端。这是我现在的代码(它不能正常工作):
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 支持异步方法,因此您可以在此处使用 TaskCompletionSource。您的代码的第二部分将如下所示:
Get["/playAnim/{id}"] = async param =>
{
var completionSource = new TaskCompletionSource<bool>();
MainWindow.PlayAnimation(() => { completionSource.SetResult(true); });
await completionSource.Task;
return "Ok";
};