0

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.

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Anil D
  • 1,989
  • 6
  • 29
  • 60

1 Answers1

0

Based on the code that you shared, I assume you're working on 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.

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.

Ram Kumaran
  • 621
  • 6
  • 12