I wrote ConcurrentQueue as Generic Abstract class in c# with limited .NET. You can see the complete mechanism at play in my app. The class provides an easy enqueue of process requests on background thread. The client does not have to bother much about the threading etc., they can just call a method to enqueue requests which they want to process in the background. With FIFO method queue does its work in the background. The derived classes of ConcurrentQueue decide two most important aspects of the queue – type of the request and the related process of the request. Type of request is taken care of by Generics and process related to request is to be implemented by the derived class. Process and request could have been implemented with Task & Delegate but I was more comfortable with straight forward methods. In some future version I might update it and implement it with Task.
Let’s take a look at the class diagram:
RequestStatus enum is currently used internally to register the status of a request in the queue. I will not discuss fields, we will know about them when we go through the code. Let’s have a look at the properties and methods:
- Count: Returns the number of requests waiting in the queue.
- IsQueueAlive: Returns Boolean to indicate whether is queue is alive to take/process requests.
- IsQueueClosed: Returns Boolean to indicate if queue is available for new request or not.
- IsQueueEmpty: Reurns Boolean to inform whether queue has requests or not.
- IsQueueHalted: Returns Boolean. True indicates queue is not processing any request and waiting to be started again.
- QueueItemEqualityComparer: The derived class determines equality comparer for the type.
- ConcurrentQueue : Constructor
- DoWhenQueueGetsEmpty: Executes on the process thread when queue gets empty. This is a virtual method for derived class to add more functionality.
- Exit: Client calls this method to signal an exit with appropriate exiting behavior. Queue is not guaranteed to exit immediately. Derived class can extend the logic of this virtual method for exiting queue process.
- HaltQueueProcess: Client calls this method to halt background process of the queue. Background process completes the current process and waits for signal (from ProceedQueueProcess) to take up next request in queue. During queue is in halt state, new requests can still be enqueued. This is a virtual method and derived class can extend it.
- ProceedQueueProcess: Client calls this method to bring the queue out of the halt.
- IsQueueAvailableForEnqueu: Derived class implements logic in this abstract method to determine whether queue should be considered as available for enqueue.
- Process: Client calls this method to enqueue request.
- ProcessRequest: The background thread calls this abstract method for processing. Each derived class implements the process for the request.
- Reset: Queue is emptied and made ready for a new enqueue.
Next, we will go through the internal code of the class.