在Asp.Net MVC项目中,我有一个Asynchronus控制器,wand我也有一个Task类型的动作来实现Asynchronus功能。
好吧,我有以下代码,
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 part始终等待CreateUserFunctionality完成。 我的目标是立即返回视图,而不是等待CreateUserFunctionality完成,因为它应该在后台继续。 请让我知道我在这里失踪了什么。
In Asp.Net MVC project I have an Asynchronus controller, wand I also have an action of type Task to implement Asynchronus functionality.
Well I have the following code,
Action startMethod = delegate() { CreateUserFunctionality(user.UserID); }; return Task.Factory.StartNew(startMethod).ContinueWith( t => { return (ActionResult)RedirectToAction("Profile", "UserProfile"); });And I also has, CreateUserFunctionality as
public void CreateUserFunctionality(int UsrId) { if (UsrId !=0) { _userService.NewFunctionality(UsrId); } }I expect that the function will start the job, CreateUserFunctionality and returns the view for me which is written in ContinueWith function. However in my case that continuewith part always waits for the CreateUserFunctionality to complete. My aim was to return the view immediatly and not wait for CreateUserFunctionality to finish, as It should continue in background. Please let me find out what I am missing here.
最满意答案
当然它会等待,因为你正在使用ContinueWith方法。如果你不想等待只是开始你的任务,并离开它。立即返回你的ActionResult:
var task = Task.Factory.StartNew(startMethod); return RedirectToAction("Profile", "UserProfile");从文档:
Task.ContinueWith方法:创建在目标任务完成时异步执行的延续。
所以它按预期工作。
Ofcourse it will wait because you are using ContinueWith method.If you don't want to wait just start your task, and leave it.Return your ActionResult immediately:
var task = Task.Factory.StartNew(startMethod); return RedirectToAction("Profile", "UserProfile");From documentation:
Task.ContinueWith Method : Creates a continuation that executes asynchronously when the target Task completes.
So it is working as expected.
更多推荐
发布评论