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; } } } }
如有疑问或者错误的地方,请跟帖,本人会第一时间答复以及相互学习,谢谢!个人会不断的上传自己的学习心得!
好了今天就先到这里,下次有时间再更新,如果存在不合理的地方,欢迎大家多多指教留言!!!