Reputation: 1761
I need to call a process from my Web API controller action asynchronously so the action doesn't wait for the process to finish to return. How is this done? I'm trying to avoid writing a message queue.
This is an example of what I am looking to do
public JsonResult Index(string key)
{
//call some process here but don't wait for it to finish,
//this would be something like logging or sending an email
// this returns immediately
return new JsonResult
{
...
};
}
Upvotes: 0
Views: 406
Reputation: 2654
You could also look at background job schedulers like hangfire or Quartz.net
Below is a nice blog entry on these solutions.
How to run Background Tasks in ASP.Net
Upvotes: 1
Reputation: 19321
If you can afford to lose your background work, you can use Task.Run()
. If it is important, use QueueBackgroundWorkItem
. For more info, take a look at this.
Upvotes: 1
Reputation: 532725
Task.Run() or ThreadPool.QueueUserWorkItem()
For logging you might want to write an asynchronous log appender, if using log4net. For email, I would consider using a drop directory and having the SMTP server pick up the mail asynchronously. Both of these would remove the complexity from the controller action and localize it in the component you're using instead.
Upvotes: 1