Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async/Await vs TPL vs WCF Service vs Web API: So many choices

My ASP.Net 4 web app calls some code that spawns a Process for a long running script. The standard output is read and the returned value is updated in the database. I would like to "fire and forget" this bit of code so that my UI remains responsive and the user doesn't have to wait around for these two operations to complete. The end result of these two operations are not needed by the calling code so I don't think I need to "await" anything and I don't need any indication of success or failure.

I'm getting confused by all of the available options. What is the best way to code this so that these two operations are just sent off on their merry way and do their thing on their own?

like image 894
beaudetious Avatar asked Mar 19 '23 11:03

beaudetious


2 Answers

I would like to "fire and forget" this bit of code

"Fire and forget" is almost always the wrong solution on ASP.NET.

so that my UI remains responsive

You can make your UI responsive without changing your server side. Just execute the request asynchronously (HttpClient for a .NET UI; AJAX for an HTML UI).

I don't need any indication of success or failure.

Ever? This is where we usually find out that "fire and forget" actually isn't what people want. A true "fire and forget" means that if the background operation never completes or has an error, then you're perfectly fine with nothing showing up in the logs.

As I said above, the best option is to handle the "asynchronous" requirement on the client side. But if you really need to do it on your server, then you have these three options:

  1. Add a persistent queue with an independent backend (e.g., Azure queue with an Azure WebJob). Your web app just adds the work to the queue and returns. The independent backend reads from the queue and does the actual processing.
  2. Use something like HangFire. This is essentially the same, except the "queue" is a database and the backend runs alongside your ASP.NET app instead of being fully independent.
  3. Use something like HostingEnvironment.QueueBackgroundWorkItem (.NET 4.5.2) or my AspNetBackgroundTasks (.NET 4.5). This is a much more dangerous option, since there is no reliable storage for the work.
like image 173
Stephen Cleary Avatar answered Apr 06 '23 18:04

Stephen Cleary


Well, "best way" may be debatable, but I would proceed with TPL using something like the following:

Task parentTask = Task.Factory.StartNew(() => SomeMethod(someParameter));

Note: If the “long running script” calls a WCF service, then the following article on WCF asynchronous programming may be helpful. http://blogs.msdn.com/b/wenlong/archive/2009/02/09/scale-wcf-application-better-with-asynchronous-programming.aspx

like image 25
Seymour Avatar answered Apr 06 '23 20:04

Seymour