But my question is there is any way to find the status of a Task using the ID we stored
No. Given an id, you cannot look up a Task
object. You'd need to store them yourself in a thread-safe dictionary like ConcurrentDictionary
, and be sure to remember to clear them from the dictionary when they complete, or you'll end up with resource leaks.
For example I am calling an API with long running task, the API calls the Task.Run and since its async, I am returning 202.
This is an extremely dangerous solution. There are several problems with it:
- Since the work is entirely in-memory (in the thread pool work queue), the work is lost anytime the server is rebooted, the hosting application is restarted, or the app pool is recycled. Two common scenarios are deploying an update to the code or applying an OS patch; either of these can cause you to lose work.
- Since the id-to-status lookup is also in-memory, any status check API calls will need to hit the same instance as the API call that started the work. This is not generally the case in server farms.
How to achieve that.
The only real solution for asynchronous messaging is a basic distributed architecture:
- A durable queue, i.e., not in-memory.
- A backend service to process the queue. This can be hosted in the same app as the web service, but I generally recommend making it an independent process.
- A system for tracking/retrieving results. This can be durable or in some (distributed) memory like Redis.
But that time, its not async, isnt it? So why everywhere saying to add Await before calling a task.run
This is because there are two different meanings of "asynchronous" here. "Asynchronous" can mean "yield the current thread". It can also mean something different at a higher level; in this case, it can mean "call an API to start an operation" - commonly called "asynchronous messaging".
When using the async
/await
keywords on ASP.NET, they are "asynchronous" in the sense that they allow the request thread to return to the thread pool. They are not "asynchronous" in the sense that they return early to the client.