gpt4 book ai didi

c# - 在后台运行异步操作方法

转载 作者:太空狗 更新时间:2023-10-29 23:53:30 25 4
gpt4 key购买 nike

有没有办法在标准操作方法中调用异步操作方法而不是等待异步方法执行(保持相同的请求对象)?

public class StandardController : Controller
{
public ActionResult Save()
{
// call Background.Save, do not wait for it and go to the next line

return View();
}
}

public class BackgroundController : AsyncController
{
public void SaveAsync()
{
// background work
}
}

我尝试使用 Task 类来完成后台工作,但是当我开始任务并且操作方法返回 View 时,请求被终止并且我的 DependencyResolver 实例被删除,所以后台任务开始抛出异常。

第一个想法是执行 Standard.Save(不调用后台任务)并返回可以在 ajax 中调用 Background.Save 方法的 View 。所以换句话说:将另一个请求调用到异步 Controller ,以启动后台任务。

主要问题是如何调用保持授权信息(在 cookie 中)和依赖解析器(在我的例子中是 autofac)的异步方法。

最佳答案

您可以在同步代码中运行一些异步方法:

public class StandardController : Controller
{
public ActionResult Save()
{
//code...
YourMethod();
//code...
return View();
}
public async void YourMethod()
{
await Task.Run(()=>{
//your async code...
});
}
}

YourMethod() 将在 Save() 完全执行之前和之后执行。

关于c# - 在后台运行异步操作方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17272870/

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