gpt4 book ai didi

C# 项目在很短的时间内为空?

转载 作者:行者123 更新时间:2023-11-30 14:22:30 25 4
gpt4 key购买 nike

我有一个 MessageQueue 类,它有一个用作队列的私有(private) List 属性。只有一种添加到队列的方法(通过 Add 方法)和一种从队列中获取的方法(通过 Next 方法)。我有一个线程正在运行,没有延迟,不断检查队列。有时,null 项会进入队列。

如果要添加的项为空,我会在 Add 方法中放置一个断点,但从未命中断点。

如果返回的项目是 null,我会在 Next 方法中放置一个断点,这会被命中。

此外,断点是在它获取项目之后但在调整队列之前设置的。奇怪的是,虽然返回的项目是null,但刚刚获取 的项目不是null!这是我的队列-

public class MessageQueue
{
private List<byte[]> queue = new List<byte[]>();

public void Add(byte[] payload)
{
if (payload == null)
{
Console.WriteLine("thats why");
}

queue.Add(payload);
}

public byte[] Next()
{
byte[] hand = queue.First();

if(hand == null)
{
Console.WriteLine("asdf");
}

queue = queue.Skip(1).ToList();

return hand;
}

public bool HasMessages
{
get
{
return queue.Count() > 0;
}
}
}

这是队列中的内容-

enter image description here

这是手中的东西-

enter image description here

因为我在队列中使用 First,所以如果没有项目就会抛出错误。

事实上,为了确定两者之间没有某种关联,我在 First 调用周围放置了一个 try-catch - 它永远不会被命中。

当 null 永远不会添加到队列中并且队列中的第一个项目不为 null 时,hand 如何为 null?

最佳答案

列表<> is not thread safe

如果您从不同的线程访问它,您会看到它处于损坏状态。使用任何 synchronization technique或来自 thread-safe collections 的任何内容

如上所述:“ConcurrentQueue 最有可能是你需要使用的”

关于C# 项目在很短的时间内为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49353835/

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