简体   繁体   English

在C#中异步运行代码

[英]Run code asynchronously in C#

I have an ASP.NET MVC app written in C#. 我有一个用C#编写的ASP.NET MVC应用程序。 One of my actions looks like this: 我的动作之一如下所示:

[HttpPost]
public async Task<ActionResult> Save(int id, MyViewModel viewModel)
{
  viewModel.SaveToDb();

  await Backup.Save(viewModel);
  return View(viewModel);
}

... ...

public class Backup
{
  async public static Task Save(IBackup item)
  {
    // do stuff
  }
}

There is actually a lot going on in the Backup.Save function. 实际上,Backup.Save函数中有很多事情。 In fact, await Backup.Save(...) is currently taking 10 seconds. 实际上, await Backup.Save(...)当前需要10秒钟。 For that reason, I want to run it in the background (asynchronously) and not (a)wait on it. 因此,我想在后台(异步)运行它,而不是(a)等待它。 I thought if I just removed the await keyword, it would work. 我以为只要删除await关键字就可以了。 However, it does not appear that is the case. 但是,事实并非如此。

How can I run Backup does save asynchronously in the background so that my users can continue using the app without long wait times? 我该如何运行Backup并在后台异步保存,以便我的用户无需长时间等待即可继续使用该应用程序?

Thank you! 谢谢!

See here for a discussion of this: Can I use threads to carry out long-running jobs on IIS? 有关此问题的讨论,请参见此处: 我可以使用线程在IIS上执行长时间运行的作业吗?

One simple alternative without having to use threads or queues would be to make an additional async call via the client, possibly via Ajax assuming the client is a browser. 一个无需使用线程或队列的简单替代方法是通过客户端(可能是通过Ajax假定客户端是浏览器)进行另一个异步调用。

If you need the view model back immediately, then potentially split this into two methods. 如果您需要立即返回视图模型,则可以将其分为两种方法。 One that gets the view model, and then you call a second method that does the save in the background. 一种获取视图模型,然后调用第二种在后台进行保存的方法。

This should work fine since if you are happy to return right away, you have already implicitly agreed to decoupled the dependency between the two actions. 这应该可以正常工作,因为如果您愿意立即返回,那么您已经隐式地同意将两个动作之间的依赖关系解耦。

It is a bit of a hack, since the client is now requesting an action it may not need to know or care about. 这有点骇人听闻,因为客户端现在正在请求可能不需要了解或关心的操作。

you can make a method that takes an action or a function (whatever you need), and runs a thread with whatever you need to run in the background. 您可以创建一个方法,该方法可以执行某个操作或一个函数(无论您需要什么),并可以在后台运行任何需要运行的线程。

Basically whatever way you choose to make it, run the method in a separate thread. 基本上,无论选择哪种方式,都可以在单独的线程中运行该方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM