# .NET 9 prioritised Channel

.NET 9 introduces `CreateUnboundedPrioritized` in `System.Threading.Channels`!

Unlike FIFO channels, it retrieves the highest priority element first, using `Comparer<T>.Default` or a custom `IComparer<T>`.

This new method allows for more flexible and efficient message processing by enabling priority based dequeuing. Instead of handling elements in a strict first in, first out (FIFO) order, `CreateUnboundedPrioritized` ensures that higher priority items are always dequeued first. This makes it particularly useful for scenarios like task scheduling, event processing, or job queues where certain operations need to be handled with greater urgency. Developers can leverage `IComparer<T>` to define custom priority rules, allowing for fine grained control over execution order.

## Example

```csharp
using System;
using System.Collections.Generic;
using System.Threading.Channels;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        // Create an unbounded prioritized channel using a custom comparer (higher numbers have higher priority)
        var channel = Channel.CreateUnboundedPrioritized<int>(new PriorityComparer());

        // Writer task to enqueue items with different priorities
        var writer = Task.Run(async () =>
        {
            await channel.Writer.WriteAsync(5);  // Medium priority
            await channel.Writer.WriteAsync(1);  // Low priority
            await channel.Writer.WriteAsync(10); // High priority
            await channel.Writer.WriteAsync(7);  // Higher than 5, lower than 10

            channel.Writer.Complete(); // Signal completion
        });

        // Reader task to dequeue items based on priority
        var reader = Task.Run(async () =>
        {
            await foreach (var item in channel.Reader.ReadAllAsync())
            {
                Console.WriteLine($"Dequeued: {item}");
            }
        });

        await Task.WhenAll(writer, reader);
    }

    // Custom comparer: higher values have higher priority
    class PriorityComparer : IComparer<int>
    {
        public int Compare(int x, int y) => y.CompareTo(x); // Reverse order for priority
    }
}
```
