I have specific problem, I want to have one separate work thread , which in some periods controls , if the buffer isn't empty. If it isn't, thread send data from buffer (ConcurrentQueue) ... Is there any good solution, which isn't much expensive for CPU??

Here is my method, it works but maybe not very well (Really i don't understrand thread synchronisation much).

public void start(object timeout){

            //Message - my own objective implementation of some tcp message
            Message m;
            while (true) {
                if (msgBuffer.Count != 0) {
                    if (msgBuffer.TryDequeue(out m)) {
                        client.SendData(MediatorPacket.GetPacketBytes(m));
                        SpinWait.SpinUntil(() => { if (msgBuffer.Count != 0) return true; else return false; });
                    }
                }
            }
        }*/
有帮助吗?

解决方案

Sounds like you're looking for a producer-consumer with blocking behavior (i.e. the consumer will block and not be scheduled until there is data in the buffer.). In that case have a look at BlockingCollection.

其他提示

Absolutely. Take a look at TPL DataFlow library. In particular, BufferBlock should fit right in with your needs. You might also find this primer an interesting read.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top