为什么Task.Factory.StartNew()。continuewith()不按预期工作(Why Task.Factory.StartNew().continuewith() Not worki

系统教程 行业动态 更新时间:2024-06-14 16:57:17
为什么Task.Factory.StartNew()。continuewith()不按预期工作(Why Task.Factory.StartNew().continuewith() Not working as expected)

在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.

更多推荐

本文发布于:2023-04-12 20:14:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/f92255e663edb95f80335db66e90a478.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不按   工作   StartNew   Factory   Task

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!