0

As a simple example, say I have an eCommerce application. An order is submitted and various notifications emails are sent (to the person ordering, to the administrator, etc).

public ActionResult SubmitOrder()
{
    SubmitOrder();
    SendNotifications();

    Return View("OrderSubmitted");
} 

I don't want the user to wait while the SendNotifications function is executing. Essentially, I want it to behave as if I called it using Ajax from the view.

How would I accomplish this?

Alex K
  • 475
  • 1
  • 5
  • 13

1 Answers1

-1

If you want your action to be async you can convert your ActionResult into async Task this will behave like ajax call from view.

Ex.

public Task<ActionResult> SubmitOrder()
{       
   var tasks = await Task.WhenAll(SubmitOrder, SendNotifications);

   return view("OrderSubmitted", tasks );
}

Something that you need to take note is you also need to convert your methods (SumitOrder/SendNotifications) to be async or use Task.Run like what @phnkha mentioned. Also this need v4.5 or if you are targeting v4.0 you need Microsoft.Bcl.Async package.

If you want tutorial on how to make your MVC controller or action async you can visit this link

Optional approach you can also use Hangfire for this kind of task.

I hope this will help you explore more!

jtabuloc
  • 2,479
  • 2
  • 17
  • 33
  • He didn't mention .Net 4.0 or 4.5 and he didn't want users to wait while the SendNotifications function is executing. Also you are lacking async modifier. Look at your code, what if SubmitOrder fail and notifications were sent? – phnkha Jan 04 '17 at 03:40
  • I'm giving him an option to explore or to start with and of course you don't want to put a full blown implementation to answer his question, right? – jtabuloc Jan 04 '17 at 03:44
  • @phnkha As of January 12, 2016 all versions of .NET lower than 4.5.2 is [no longer supported by microsoft](https://blogs.msdn.microsoft.com/dotnet/2014/08/07/moving-to-the-net-framework-4-5-2/), so I think it is safe to just give answers in 4.0 compatible code. – Scott Chamberlain Jan 04 '17 at 03:47
  • @jtabuloc however, that being said, Microsoft.Bcl.Async [is not supported in ASP.NET](http://stackoverflow.com/a/23629827/80274). – Scott Chamberlain Jan 04 '17 at 03:49
  • Thanks men, I'm not aware of that! – jtabuloc Jan 04 '17 at 03:52