I have a main thread which should process data coming from several worker threads.
But this data is not a specific class.
There are around 6-7 classes, and I need to pass one of this class to the main thread from worker threads.
Previously I had only one class which was passed across threads. I was using;
BlockingCollection<MyClass> mainQueu = new BlockingCollection<MyClass>(new ConcurrentQueue<MyClass>());
So I was pushing MyClass instances from several threads to mainQueu and main thread was trying to take from the mainQueu.
But what if I have more than one classes. Which way is better?
-
Having a queue for each type of class:
Of course there should be another queue of type maybe enum, specifying which class is pushed to the queue. And main thread always tries to take from this queue. As soon as any item comes, it will takes from related queue.
-
Casting:
Having only one main queue, and in mainQueue class, I can have object member.
And enum which specifies type of object member.
And I can convert class to object when pushing to queue, and than in main thread I can cast it back to original class.
Hope it is clear.
Many thanks,regards
A useful trick here is to just have the worker as a queue of delegates; for example,
Action. Then the caller can enqueue the appropriate method and (via captured varialbes) any necessary state.Say, for example, you have a
void Enqueue(Action)method; the caller could do:(where
targetObject.Methodis avoid Method() {...}), or can do something like:(where
fooandbarare local to the code that wants the work done)so we’ve passed lots of state at once, and not once had to think about types – just operations.