Note that โcollectionsโ like the one you are displaying are usually exposed through IEnumerable<T> . If you have control over the API itself, I would use IEnumerable<T> instead of an approach based on GetNext() . However, if you do not, just do the conversion ...
I would wrap this API to show it as an IEnumerable<T> . Then you can use Parallel.ForEach :
private IEnumerable<T> EnumerateWidgets<T>(ICollectionWidget<T> widgets) { T element = widgets.GetNext(); while (element != null) { yield return element; element = widgets.GetNext(); } }
Then you can use:
Parallel.ForEach(EnumerateWidgets(widgetCollection), widget => {
This will prevent threading issues when listing your widgets (since the listing will be single-threaded), but you can process your collection in parallel.
source share