priyanka.sarkar
priyanka.sarkar

Reputation: 26498

How to return a value to client application from WebAPI but at the same time some other operation needs to be performed?

I have a WebAPI method as under

[HttpPost]
[Route("AddSubProduct")]
public string InsertSubProduct(SubProduct subproduct)
{
   try
   {
      subProductRepository.InsertSubProduct(subproduct);

      // This message must be returned to the client application as soon
      // as the product is created
      subproduct.ToString();

      // This will happen parallely 
      DoSomethingElse(subproduct);
   }
   catch (Exception ex)
   {
      throw ex;
   }
}

As can be figured out that subproduct.Tostring() will be first sent to the client application immediately (as soon as the Product is created) and DoSomethingElse will work independently (though the current implementation is not like that, we have to do it). As can be figured out that I cannot use a return statement here.

How will I do that?

Upvotes: 1

Views: 407

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

You'll need to queue work on a background thread. I suggest using HostingEnvironment.QueueBackgroundWorkItem if you're using .NET 4.5.2. If you're on a previous version, useBackgroundTaskManager. Both will register their work with the ASP.NET runtime:

[HttpPost]
[Route("AddSubProduct")]
public string InsertSubProduct(SubProduct subproduct)
{
    subProductRepository.InsertSubProduct(subproduct);

    HostingEnvironment.QueueBackgroundWorkItem(cancellationToken =>
                                               DoSomethingElse(subproduct));
    return subproduct.ToString();
}

If you're going to be doing this often with concurrent requests, you should consider queuing up and have a single thread dequeue and process them. If persistence is of matter here, you'll need to choose a different route.

Side note - don't catch exceptions you can't handle. Especially, don't use throw ex, you lose the stacktrace.

Upvotes: 1

Related Questions