简体   繁体   English

继续执行方法,无需等待其他方法执行

[英]Continue method execution without waiting for other method execution

I want to call a method inside some method and do not want the process to wait or take time on other method completion. 我想在某个方法内调用一个方法,并且不希望该过程在其他方法完成时等待或花费时间。

like this 像这样

public ActionResult Insert(int userId)
{
     _userService.Insert(userId);
     SyncUserInSomeOtherCollection(userId);
     return new EmptyResult();
}

private SyncUserInSomeOtherCollection(int userId)
{
  //Do Sync work which will actually take some time
}

I want to make SyncUserInSomeOtherCollection() work in such a way so that the main method return result without any wait. 我想使SyncUserInSomeOtherCollection()以这种方式工作,以便主方法无需等待即可返回结果。

I tried to run a task like this 我试图运行这样的任务

Task.Run(async () => await SyncUserInSomeOtherCollection(userId)).Result;

But not sure if this a good approach to follow. 但是不确定这是否是一个好的方法。

Based on the code that you shared, I assume you're working on ASP.NET. 根据您共享的代码,我假设您正在使用ASP.NET。 I've come across same scenario and found QueueBackgroundWorkItem to work for me, it also allows you to have graceful shutdown of your long running task when Worker Process is stopped / shutdown. 我遇到过相同的情况,发现QueueBackgroundWorkItem对我有用,当Worker Process停止/关闭时,它还允许您正常关闭长时间运行的任务。

HostingEnvironment.QueueBackgroundWorkItem(cancellationToken =>
{
  if (!cancellationToken.IsCancellationRequested)
  {
    //Do Action
  }
  else
  {
    //Handle Graceful Shutdown
  }
}

There are more ways to accomplish this. 还有更多方法可以实现这一目标。 I suggest you go through this excellent article by Scott Hanselman. 我建议您阅读Scott Hanselman的这篇精彩文章

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

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