Channel简单使用

Channel 是啥与其作用

查看官网介绍

https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.channels.channel-1?view=net-6.0

code:

using System.Collections.Generic;
using System.Threading.Channels;
using System.Threading.Tasks;
using System.Linq;
namespace QzjcService.Helper
{

    public class ChannelHelper<T>
    {
        private static Channel<T> channel;
        private static readonly object lockobj = new object();
        static ChannelHelper()
        {
            channel = Channel.CreateBounded<T>(10000);//创建有限容量的channel
            //channel = Channel.CreateUnbounded<T>();////创建无限容量的channel,看电脑配置了
        }


        public static Channel<T> CreateChannelInstals()
        {
            if (channel == null)
            {
                lock (lockobj)
                {
                    if (channel == null)
                    {
                        channel = Channel.CreateBounded<T>(10000);
                    }
                }
            }
            return channel;
        }

        /// <summary>
        /// 入队通道
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static async Task<bool> EnQueueByChannel(T entity)
        {
            try
            {
                var _channel = CreateChannelInstals();
                await _channel.Writer.WriteAsync(entity);
                return true;
            }
            catch (System.Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 出队通道, 返回一个对象
        /// </summary>
        /// <returns></returns>
        public static async Task<T> DeQueueByChannelSingalObject()
        {
            try
            {
                var _channel = CreateChannelInstals();
                var entity = await _channel.Reader.ReadAsync();
                return entity != null ? (T)entity : default;
            }
            catch (System.Exception)
            {
                return default;
            }
        }

    }
}

 

posted @ 2022-07-21 15:52  天天向上518  阅读(472)  评论(0编辑  收藏  举报