.NET 9 中的 UnboundedPrioritizedChannel

。.NET 9 中的 UnboundedPrioritizedChannel

Intro

.NET 9 Preview 5 中引入了一个支持优先级的 Channel,对于我们需要实现支持优先级的内存队列来说变得更加方便了

New API

namespace System.Threading.Channels
{
    public partial class Channel
    {
        public static System.Threading.Channels.Channel<T> CreateUnboundedPrioritized<T>() { throw null; }
        public static System.Threading.Channels.Channel<T> CreateUnboundedPrioritized<T>(System.Threading.Channels.UnboundedPrioritizedChannelOptions<T> options) { throw null; }
    }
    public sealed partial class UnboundedPrioritizedChannelOptions<T> : System.Threading.Channels.ChannelOptions
    {
        public System.Collections.Generic.IComparer<T>? Comparer { get; set; }
    }
}

引入了新的 Channel.CreateUnboundedPrioritized 方法来创建支持优先级的 channel,就像 API 名字一样,这个 Channel 是一个 Unbounded channel,对于 BoundedChannel 的支持有一个 Github issue,感兴趣的朋友可以去看下:

https://github.com/dotnet/runtime/issues/101292

Sample

var c = Channel.CreateUnboundedPrioritized<int>();

await c.Writer.WriteAsync(1);
await c.Writer.WriteAsync(5);
await c.Writer.WriteAsync(2);
await c.Writer.WriteAsync(4);
await c.Writer.WriteAsync(3);
c.Writer.Complete();

while (await c.Reader.WaitToReadAsync())
{
    while (c.Reader.TryRead(out int item))
    {
        Console.WriteLine(item);
    }
}

默认会使用默认的比较器,我们也可以实现我们自己的比较器,实现自己的优先级比较,下面是一个简单的反向输出的示例

file sealed class ReverseComparer : IComparer<int>
{
    public int Compare(int x, int y)
    {
        return y.CompareTo(x);
    }
}
var c = Channel.CreateUnboundedPrioritized<int>(new()
{
    Comparer = new ReverseComparer()
});

await c.Writer.WriteAsync(1);
await c.Writer.WriteAsync(5);
await c.Writer.WriteAsync(2);
await c.Writer.WriteAsync(4);
await c.Writer.WriteAsync(3);
c.Writer.Complete();

while (await c.Reader.WaitToReadAsync())
{
    while (c.Reader.TryRead(out int item))
    {
        Console.WriteLine(item);
    }
}

9be37d0c2cd868df992c06467462932a.png

output

从输出结果可以看出来已经 channel 中的消息排好序了,默认从小到大,第二个示例我们使用了自定义的一个比较器变成了从大到小

More

新的 UnboundedPrioritizedChannel 的 priority 比较也是基于 PriorityQueue 来实现的,使用 PriorityQueue 代替了 UnboundedChannel 里的 ConcurrentQueuePriorityQueue 的使用也非常的巧妙,使用了一个 PriorityQueue<bool, T> 具体代码可以参考 PR: https://github.com/dotnet/runtime/pull/100550

0a925c57f80f92ec6d34344515bfe754.png

UnboundedPrioritizedChannel

References

  • https://github.com/dotnet/runtime/issues/62761

  • https://github.com/dotnet/runtime/pull/100550

  • https://github.com/dotnet/runtime/issues/101292

  • https://github.com/WeihanLi/SamplesInPractice/blob/main/net9sample/Net9Samples/PriorityChannelSample.cs

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值