gpt4 book ai didi

c# - 如何在满足条件之前阻止操作?

转载 作者:太空狗 更新时间:2023-10-29 20:51:46 24 4
gpt4 key购买 nike

我正在运行这段代码,它使用了相当多的 CPU,尽管它大部分时间什么都不做。

while (this.IsListening)
{
while (this.RecievedMessageBuffer.Count > 0)
{
lock (this.RecievedMessageBuffer)
{
this.RecievedMessageBuffer[0].Reconstruct();
this.RecievedMessageBuffer[0].HandleMessage(messageHandler);
this.RecievedMessageBuffer.RemoveAt(0);
}
}
}

在满足条件之前阻止的最佳方法是什么?

最佳答案

使用WaitHandle

WaitHandle waitHandle = new AutoResetEvent();

// In your thread.
waitHandle.WaitOne();

// In another thread signal that the condition is met.
waitHandle.Set();

您还可以考虑更改类的接口(interface),以便在有新数据要读取时引发事件。然后您可以将您的代码放入事件处理程序中。

关于c# - 如何在满足条件之前阻止操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10974708/

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