Question on C# threading with RFID

女生的网名这么多〃 提交于 2019-12-03 21:01:38

I would suggest that, rather than using events, you use a concurrent queue data structure and a multiple producer, single consumer model. Think of the tag reader threads as producers, and the processing thread as consumers.

When a thread receives a tag from a reader, it adds that tag to the queue, not worrying about duplicates or anything. Heck, you might want that duplicate information at some point. No reason to throw it out right here.

The consumer waits on the queue, taking items off and processing them one at a time.

The BlockingCollection class is perfect for this.

// Shared queue.  Assuming that a tag is simply a string.
BlockingCollection<string> TagQueue = new BlockingCollection<string>();

// Tag reader threads (producers)
while (!ShutdownMessageReceived)
{
    string tag = GetTagFromReader(); // however that's done
    TagQueue.Add(tag);
}

// Processing thread (consumer)
while (!ShutdownMessageReceived)
{
    string tag = TagQueue.Take();
    // process the tag
}

BlockingCollection supports multiple producers and consumers, so you can have as many of each as you like. The Take method will block until an item is available. It's a non-busy wait, so there's no polling overhead.

This kind of thing is very easy to implement with BlockingCollection, and makes for clean and simple code that performs very well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!