Phase 13 of 30 · Topic 13.4

`PriorityQueue<TElement, TPriority>` Binary Min-Heap Internals

1Concept

`PriorityQueue<TElement, TPriority>` (.NET 6+) implements a binary min-heap where elements are dequeued in ascending priority order in O(log N) time, avoiding custom tree structures.

2Architecture Diagram

Binary Min-Heap Queue:
                 [ Task: 'P0 Urgent' (Priority: 0) ]
                            /               \
           [ Task: 'P1 High' (1) ]    [ Task: 'P2 Normal' (2) ]
                      /
         [ Task: 'P3 Low' (3) ]

3Code Example

C# 13 & .NET 9
using System;
using System.Collections.Generic;

public class PriorityQueueDemo
{
    public static void Main()
    {
        var pq = new PriorityQueue<string, int>();

        // Enqueue (Item, Priority - lower number = higher priority)
        pq.Enqueue("Send Low-Priority Digest Email", 10);
        pq.Enqueue("CRITICAL: Database Failover Alert", 0);
        pq.Enqueue("Process User Order #501", 2);

        Console.WriteLine("--- Processing Queue by Priority ---");
        while (pq.TryDequeue(out string? task, out int priority))
        {
            Console.WriteLine($"[Priority {priority}] -> {task}");
        }
    }
}

4Expected Output

--- Processing Queue by Priority ---
[Priority 0] -> CRITICAL: Database Failover Alert
[Priority 2] -> Process User Order #501
[Priority 10] -> Send Low-Priority Digest Email

5Key Takeaways

  • Enqueue and Dequeue operations run in O(log N) time.
  • Pass a custom `IComparer<TPriority>` to change min-heap to max-heap behavior.
  • Ideal for Dijkstra pathfinding, rate limiters, and task scheduling.