I have a loop that looks something like this:
var list = new List<float>();
while (list.Count < wantedNumberOfJobs)
{
var resource = ... //gets the resource
lock (resource)
{
ThreadPool.QueueUserWorkItem(DoWork, /*wrap resource and list into an object*/);
}
}
//continue pass this point when all the threads are finished
And the work method:
private void DoWork(object state)
{
var list = (/*wrapperObject*/)state.List;
var someFloat = //do the work to get the number
lock (list)
{
list.Add(someFloat);
}
}
Essentially I want to do a large, but a specific (given by wantedNumberOfJobs) number of jobs done. Each of these jobs inserts a single item into the list as you can see in the DoWork method.
I am not certain that this code is assuring me that list will contain wantedNumberOfJobs items past the designated point. I’d also like to limit the number of active threads. I’ve used the System.Threading.Semaphore class, but am not sure this is the best solution.
I’d appreciate any help. Thanks!
Perhaps you can use Parallel.For, like so: