Domanda

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; });
                    }
                }
            }
        }*/
È stato utile?

Soluzione

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.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top