gpt4 book ai didi

c# - BlockingCollection 多个消费者

转载 作者:太空狗 更新时间:2023-10-29 20:40:01 25 4
gpt4 key购买 nike

我有以下代码,其中包含一个生产者线程和多个消费者线程。你知道多个消费者是否是线程安全的。例如,线程 1 是否有可能正在消费,而线程 2 是否并行消费并更改线程 1 中使用的项目的值?

namespace BlockingColl
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
try
{
for (int i = 0; i < 3; i++)
{

ThreadPool.QueueUserWorkItem((x) =>
{
foreach (var item in bc.GetConsumingEnumerable())
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " - " + item + " - " + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"));
}
});
}
}
catch (Exception)
{

throw;
}
}

private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < 3; i++)
{

ThreadPool.QueueUserWorkItem((x) =>
{
Cache.Consume();
});
}


for (int i = 0; i < 50000; i++)
{
Cache.bc.TryAdd(new Client() { ClientId = i, ClientName = "Name" + i });
}
}
}

static class Cache
{
public static BlockingCollection<Client> bc = new BlockingCollection<Client>();


public static void Consume()
{
foreach (var item in bc.GetConsumingEnumerable())
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " - " + item + " - " + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"));
}
}
}

public class Client
{
public int ClientId { get; set; }
public string ClientName { get; set; }
}
}

提前致谢

最佳答案

一旦您使用了一个元素,它就会从集合中移除,因此其他线程将无法访问它(至少通过集合)。

Cache 对我来说更像是一个缓冲区。无论如何,它在阻塞集合之上添加了什么?缓存能够使用它自己的元素很奇怪。

关于c# - BlockingCollection 多个消费者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13195474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com