问题
I'm new to using Blocking Collection and threading and want to make sure I'm following best practice. I'm using a third party API that is not thread safe. I will be making multiple simultaneous requests to the API, so I need to add these requests to a queue and process them one after another. To do this I have a blocking collection:
BlockingCollection<myEventArgs> myTasks = new BlockingCollection<myEventArgs>();
private void myEventHandler(object sender, myEventArgs e)
{
myTasks.Add(e);
}
private void doWork()
{
while (myTasks.IsCompleted == false)
{
//Do some work here with the third party API.
var eArgs = myTasks.Take();
//Sometimes I have a background (thread safe) task to perform.
//This is submitted to the thread pool.
Task.Run(() => doSomeBackgroundWork());
}
}
Sometimes I will have a thread safe background task I want to perform. For example, the API calls are asynchronous and I need to poll the third party system to check if a task is complete. I don't want this to prevent the BlockingCollection from processing the next task, so I submit this to the thread pool. Once the thread pool task is complete it will fire an event, which adds a new task to the BlockingCollection.
Is this solution appropriate & is there anything that could go wrong with this? Am I correct to assume that the doWork method that processes items from the BlockingCollection will always run in the same thread? And when I fire events from the threadpool, only the event will run on the thread pool, and not the subsequent doWork method?
回答1:
Is this solution appropriate
Basically, yes. It is a Producer/Consumer situation and that's precisely what the BlockingCollection is for.
is there anything that could go wrong with this?
You have to be very sure that the doSomeBackgroundWork()
is thread-safe with respect to your doWork() code.
It might be a good idea to put a ceiling on Your blockingcollection, dependng on how many myEventArgs can be pushed.
回答2:
I know this is an old thread, but for the sake of readers, I would like to point out, that doing it this way, is the same as just spawning threads without a blocking collection, thus removes the whole point of BlockingCollection.
What would be more appropriate in this case, is to manage the number of threads, and only spawn a specific number of threads, while consuming the BlockingCollection, and that would make sure not too many threads get spawned at the same time
来源:https://stackoverflow.com/questions/40339390/c-sharp-blocking-collection-and-threading