Is there a built in (or at least recommended) way to limit a task to only one running instance at the same time?
I have an asynchronous process that is handled by a task. This task can be created multiple places, but only one instance of it should ever be running at once.
Should I just wrap the task creation in a mutex (with the task itself releasing the mutex before deleting itself)?
Given the constraint of having at most one instance of this task, I think the built-in (recommended) method would be to let the one task exist permanently. The task would:
- Wait for direct task notification (or perhaps a queued event)
- Process the notification / event
The task notifications (or queued events) can come from many different places – even many different tasks if needed.
The concept of just having the task exist once is the best idea. You can’t do the mutex, as only the app that took the mutex can release it, so that can’t be the task itself (you could use a semaphore). The question is, should that task wanting to start up the task block if the task is already running?
An alternative solution would be for there to be a global flag with the indication that the task is running (maybe also have the handle). If a task wants this task to be running, it could start a critical section or take a mutex, test the flag, if not running mark running, end the critical section and create the task, while if already running just end the critical section.