gpt4 book ai didi

c# - .NET MVC Fire and Forget Method 也立即返回 View

转载 作者:行者123 更新时间:2023-11-30 21:43:51 24 4
gpt4 key购买 nike

我正在寻找 Fire & Forget 方法的最佳解决方案,并立即返回 View 。据我所知,我是否将 Action 的返回类型设置为 Task<ActionResult>await它将工作的异步方法,但 Action 也在等待异步方法完成,然后按预期 返回 View 。

另一方面,如果我不这样做 await异步方法,方法的执行将在View之后被切断返回。

我想问的是,对于这种情况,最好的解决方案是什么?我的代码是这样的:

public class DefaultController : Controller
{
// GET: Default
public async Task<ActionResult> Index()
{
await Asynchronous();
return View();
}
public async Task Asynchronous()
{
var FilePath = ControllerContext.HttpContext.Server.MapPath("~/HelloWorld.txt");
for(int i = 0; i <= 100; i++)
{
await Task.Delay(15000); // Wait 15 Seconds.
System.IO.File.AppendAllLines(FilePath, new string[] { i.ToString() });
}
}
}

最佳答案

I'm looking on best solution for Fire & Forget a method at the Action and return View immediately

这取决于“最佳”的含义。 ASP.NET 上的即发即弃本质上是不安全的,因此您希望代码的安全程度各不相同。

如果您的应用程序必须继续执行,那么唯一安全的系统是让您的操作处理程序将它想要执行的操作写入安全存储机制(例如,Azure Queue、MSMQ 或 SQL Server ).一旦安全存储,您的操作方法就可以返回。然后,您还将拥有一个独立的后台进程(例如,Azure Function、Win32 服务,或者可能是您的 ASP.NET 进程中的一个线程,前提是您非常注意它的托管方式)。该后台进程将从安全存储中读取并执行实际工作。

如果您的应用偶尔会“丢失”工作(在向客户端返回成功之后),那么您可以使用安全性较低的机制,例如用于 .NET 4.5.2 的 HostingEnvironment.QueueBackgroundWorkItem ,或者我的 AspNetBackgroundTasks library对于早期版本。

my blog post on the subject 中列出了其他替代方案.

关于c# - .NET MVC Fire and Forget Method 也立即返回 View,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41309379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com