Heinrich
Heinrich

Reputation: 1761

Web API, call process asynchronously from controller action

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

Answers (3)

Julien Jacobs
Julien Jacobs

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

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.

http://blogs.msdn.com/b/webdev/archive/2014/06/04/queuebackgroundworkitem-to-reliably-schedule-and-run-long-background-process-in-asp-net.aspx

Upvotes: 1

tvanfosson
tvanfosson

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

Related Questions