首页 > 编程语言 >[转]C#阻塞队列BlockingCollection

[转]C#阻塞队列BlockingCollection

时间:2023-05-30 17:47:47浏览次数:47  
标签:C# 代码 阻塞 队列 线程 消息 BlockingCollection

BlockingCollection是一个比较冷门的类,我们先看下官方对这个类的定义:

简单来说,BlockingCollection就是一个线程安全的阻塞队列,利用阻塞这个特性,我们可以实现进程内的生产者-消费者模式,比如消息转发、日志记录等。

下面我们看一个例子,其用来实现消息转发,先定义一个MessageDistributer类,代码如下:

上面的代码很简单,使用BlockingCollection定义一个消息队列,然后使用AddMessage方法向队列中添加消息。重点看一下Process方法,里面写了一个死循环,里面调用BlockingCollection的Take方法,当队列中如果没有消息时,则阻塞队列,所以并不会一直循环。等到有新消息进来时,它就会继续处理。还有一个,我们在这个类中使用单独的线程来作执行Process方法。我们再看一下调用的地方,代码如下:

这里的代码就不多解释了,就是实例化MessageDistributer类,并开启线程,然后接收客户端输入的消息,我们运行一下,看下效果。如下:

这个简单的例子就结束了,大家可以按这个思路写个日志记录的类,思路就是单独使用一个线程轮询阻塞队列。其实还可以将Action委托作为消息放到队列中,这样可以实现一个任务执行器。代码如下:

到这里就可以说结束了,不过我们可以利用ManualResetEvent来自己实现一个简单的阻塞队列,如果你有兴趣,可以接着往下看。ManualResetEvent使用信号来做线程间的通信,当队列为空时,我们一直阻塞着线程就行。简单实现一个,代码如下:

上面的代码我就不多解释了,也比较简单,主要就是为队列的时候阻塞线程(WaitOne),添加项的时候发送信号(Set)。然后用自己封装的BlockingQueue替换消息转发类中BlockingCollection,最后运行正常,我就不再演示了。

最后总结一下,BlockingCollection这个类,我们平时用的比较少,如果你有在进程内用到消息订阅或单独开线程跑任务的场景时,你可以留意一下它,当然你也可以用Timer来实现。如果今天的内容能帮到你一点点,就给个赞吧(关注就更好了),拜拜~~

转自 https://blog.csdn.net/sD7O95O/article/details/110358395

标签:C#,代码,阻塞,队列,线程,消息,BlockingCollection
From: https://www.cnblogs.com/castlewu/p/17443883.html

相关文章

  • nuscene 数据集
    nuscenes数据集官网:https://nuscenes.org/fromnuscenes.nuscenesimportNuScenesnusc=NuScenes(version='v1.0-mini',dataroot='/media/algo/data_1/project_others/0000paper/lss/nuScenes/mini/',verbose=True)nusc.list_scenes()my_scene=n......
  • ROCKETMQ
    配置环境变量(ROCKETMQ_HOME)修改runserver.cmd1、进入bin目录下找到runserver.cmd文件,用编辑器打开,因为RocketMQ默认需要2g运行内存,做为测试用,就只要最低配置就好了,注释原有的NameServer的配置,在其前面加上rem注释掉,remset"JAVA_OPT=%JAVA_OPT%-server-Xms2g-Xmx2g-Xmn1......
  • 兼容IE,Chrome 文本控制显示三行
    谷歌浏览器得行数控制不兼容ie,加个高度限制解决。(max-height:66px;)css:.txt{display:block;height:auto;max-height:66px;overflow:hidden;text-overflow:ellipsis;word-wrap:break-word;white-space:normal!important;-webkit-line-clamp:3;......
  • leetcode 257. Binary Tree Paths
    Givenabinarytree,returnallroot-to-leafpaths.Forexample,giventhefollowingbinarytree: 1/\23\5Allroot-to-leafpathsare:["1->2->5","1->3"]#Definitionforabinarytreenode.#classTreeNode(obje......
  • leetcode 202. Happy Number
    Writeanalgorithmtodetermineifanumberis"happy".Ahappynumberisanumberdefinedbythefollowingprocess:Startingwithanypositiveinteger,replacethenumberbythesumofthesquaresofitsdigits,andrepeattheprocessuntilthe......
  • leetcode 671. Second Minimum Node In a Binary Tree
    Givenanon-emptyspecialbinarytreeconsistingofnodeswiththenon-negativevalue,whereeachnodeinthistreehasexactlytwoorzerosub-node.Ifthenodehastwosub-nodes,thenthisnode'svalueisthesmallervalueamongitstwosub-nodes.G......
  • python split space
    发现自己写python的空格split还挺多坎的,尤其是最后一个是空格的情形:defsplit(s):i=0ans=[]whilei<len(s):start=i#findspacewhilei<len(s)ands[i]!='':i+=1ans.append(s[start:i])......
  • leetcode 409. Longest Palindrome
    Givenastringwhichconsistsoflowercaseoruppercaseletters,findthelengthofthelongestpalindromesthatcanbebuiltwiththoseletters.Thisiscasesensitive,forexample"Aa"isnotconsideredapalindromehere.Note:Assumethelength......
  • leetcode 747. Largest Number At Least Twice of Others
    Inagivenintegerarraynums,thereisalwaysexactlyonelargestelement.Findwhetherthelargestelementinthearrayisatleasttwiceasmuchaseveryothernumberinthearray.Ifitis,returntheindexofthelargestelement,otherwisereturn-1.Ex......
  • leetcode 107. Binary Tree Level Order Traversal II
    Givenabinarytree,returnthebottom-uplevelordertraversalofitsnodes'values.(ie,fromlefttoright,levelbylevelfromleaftoroot).Forexample:Givenbinarytree[3,9,20,null,null,15,7],3/\920/\157returnits......