Thread Safe Deferred Callback
Explore how to create a thread safe deferred callback system in C#. Understand the use of Monitors for synchronization and priority queues to schedule callbacks efficiently. This lesson guides you through designing an execution thread that waits appropriately and processes callbacks in the correct order without busy waiting.
We'll cover the following...
Thread Safe Deferred Callback
Design and implement a thread-safe class that allows registration of callback methods that are executed after a user specified time interval in seconds has elapsed.
Solution
Let us try to understand the problem without thinking about concurrency. Let's say our class exposes an API called addAction() that'll take a parameter action, which will get executed after user specified seconds. Anyone calling this API should be able to specify after how many seconds our class should invoke the passed-in action.
One naive way to solve this problem is to have a busy thread that continuously loops over the list of actions and executes them as they become due. However, the challenge here is to design a solution which doesn't involve a busy thread.
One possible solution is to have an execution thread that maintains a priority queue (min-heap) of actions ordered by the time remaining to execute each of the actions. The execution thread can sleep for the duration equal to the time duration before the earliest action in ...