后台工作者阻止 MVC 控制器操作

发布于 2024-09-26 07:22:54 字数 498 浏览 1 评论 0原文

我想在新线程/异步中从 ASP.NET MVC 控制器操作运行一些代码。我不关心响应,我想在异步方法在后台运行时触发并忘记并向用户返回一个视图。我认为 BackgroundWorker 类适合这个?

public ActionResult MyAction()
{
    var backgroundWorker = new BackgroundWorker();
    backgroundWorker.DoWork += Foo;
    backgroundWorker.RunWorkerAsync();

    return View("Thankyou");
}

void Foo(object sender, DoWorkEventArgs e)
{
    Thread.Sleep(10000);
}

为什么这段代码会导致返回视图之前有 10 秒的延迟?为什么视图没有立即返回?

更重要的是,我需要做什么才能使这项工作成功?

谢谢

I want to run some code from an ASP.NET MVC controller action in a new thread/asynchronously. I don't care about the response, I want to fire and forget and return the user a view while the async method runs in the background. I thought the BackgroundWorker class was appropriate for this?

public ActionResult MyAction()
{
    var backgroundWorker = new BackgroundWorker();
    backgroundWorker.DoWork += Foo;
    backgroundWorker.RunWorkerAsync();

    return View("Thankyou");
}

void Foo(object sender, DoWorkEventArgs e)
{
    Thread.Sleep(10000);
}

Why does this code cause there to be a 10 second delay before returning the View? Why isnt the View returned instantly?

More to the point, what do I need to do to make this work?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

今天小雨转甜 2024-10-03 07:22:54

您可以开始新线程:

public ActionResult MyAction()
{
    var workingThread = new Thread(Foo);
    workingThread.Start();

    return View("Thankyou");
}

void Foo()
{
    Thread.Sleep(10000);
}

You can just start new thread:

public ActionResult MyAction()
{
    var workingThread = new Thread(Foo);
    workingThread.Start();

    return View("Thankyou");
}

void Foo()
{
    Thread.Sleep(10000);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文