1

Context: we have a task which might take from 30 seconds to 5 minutes depending on a service we are consuming in some Azure Functions.

We are planning to monitor the current status of that task object to make sure it's running and has not been cancelled/faulted.

There are two ways to go around it:

  • Create a Task, run it and then cancel it when the main task is finished. Alternatively, maybe use Task.Delay along with a while with a condition.
  • Create a Thread, run it and wait for it to finish (with a while condition to avoid a while that runs forever).

We have done some research and have realised that both have pros and cons. But we are still not sure about which one would be the best approach and why.

In a similar scenario, what would you use? A task, a thread, or something else?

1 Answers1

0

Using a thread is a bit wasteful, but slightly more reliable.

  1. It is wasteful because each thread allocates 1 MB of memory just for its mere existence.

  2. It is more reliable because it doesn't depend on the availability of ThreadPool threads for running a timer event. A sudden burst in demand for ThreadPool threads could leave the ThreadPool starved for several seconds, or even minutes (in extreme scenarios).

So if wasting 1 MB of memory is a non-issue for the app, use a thread. On the other hand if the absolute precision in the timing of the events is something unimportant, use a task.

You could also use a task started with the option LongRunning, but this is essentially a thread in disguise.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104