【问题标题】:Why Task.Factory.StartNew().continuewith() Not working as expected为什么 Task.Factory.StartNew().continuewith() 没有按预期工作
【发布时间】:2014-01-16 14:19:40
【问题描述】:

在 Asp.Net MVC 项目中,我有一个异步控制器,我还有一个任务类型的动作来实现异步功能。

我有以下代码,

Action startMethod = delegate() { CreateUserFunctionality(user.UserID); };
            return Task.Factory.StartNew(startMethod).ContinueWith(
                    t =>
                    {
                        return (ActionResult)RedirectToAction("Profile", "UserProfile");
                    });

我也有,CreateUserFunctionality as

public void CreateUserFunctionality(int UsrId)
{
  if (UsrId !=0)
  {
     _userService.NewFunctionality(UsrId);
  }
}

我希望该函数将启动工作,CreateUserFunctionality 并为我返回用ContinueWith 函数编写的视图。但是在我的情况下, continuewith 部分总是等待CreateUserFunctionality 完成。我的目标是立即返回视图,而不是等待 CreateUserFunctionality 完成,因为它应该在后台继续。请让我找出我在这里缺少的东西。

【问题讨论】:

  • 这与 async-await 有什么关系?
  • 您知道CreateUserFunctionality 可能永远无法正确完成吗?您将如何从错误中恢复?

标签: c# asp.net asp.net-mvc asynchronous async-await


【解决方案1】:

当然它会等待,因为你正在使用ContinueWith 方法。如果你不想等待,只需开始你的任务,然后离开它。立即返回你的 ActionResult:

 var task = Task.Factory.StartNew(startMethod);
 return RedirectToAction("Profile", "UserProfile");

来自documentation:

Task.ContinueWith 方法:创建一个执行的延续 异步在目标任务完成时。

所以它按预期工作。

【讨论】:

  • 谢谢 Selman22,那么 actionresult 的类型应该是什么,目前我有它,public Task<ActionResult> UserUpdate(UserModel model)。我需要从 actionresult 中删除任务吗?
  • 是的,你可以删除它
  • 感谢它的魅力,对我来说也是一个很好的学习曲线。
猜你喜欢
  • 2014-08-04
  • 2021-01-03
  • 2018-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-08
相关资源
最近更新 更多