I am trying to implement a producer/consumer pattern for a stream of data that I am reading off of a controller asynchronously. I would like to use the BlockingCollection<T>
in order to do so, but want to make sure I get the desired results. My consumer would look something like this:
// make sure there is actually some data in the buffer
if (!this.buffer.IsCompleted)
{
// attempt to read from the buffer
data = this.buffer.Take();
// construct the message object
message = this.ConvertToMessageObject(data);
}
Does the IsCompleted
property actually block? So that if another thread was going to access the buffer, I would like it to wait and make sure that the buffer is actually not "completed" before calling on the Take
method.
In my application, the desired effect would be to allow me to avoid constructing a new message object when the buffer is in fact empty. So that's why I am checking IsCompleted
before going and trying to Take
.
Additionally... I understand that the Take
method no longer blocks once IsAddingCompleted = true
. So I wouldn't want a consumer to grab data from the Take
method that isn't valid, which it would have no choice of doing (if the consumer didn't know about the completed status). I think am having a really hard time trying to explain what I am worried about here...