1

I am new to threading world, I have less(no) idea about threading. Please give me support to solve my following issue.

  1. I have 2 generic lists (list1, list2)
  2. I will iterate trough list1
  3. Do some processing and need to store result in list2

I need to process items in list1 batch by batch in given number of threads, store all outputs in single list (list2)

Q1. How to make batches from list1 and give to threads ?
Q2. How we identify when one tread has finished its operation ?
Q3. How we give next item to finished tread ?
Q4. Will it be cause accessing issues to list2 (since it is accessed by multiple threads) ?

3
  • please show some code... what have you tried so far ?
    – Yahia
    Aug 19, 2011 at 7:21
  • I have big code and harder(and unpractical)to show here. As I said I have NO idea how to do this with threading. My code only works in a Single Thread, What I need to do is make it multi-threaded Aug 19, 2011 at 7:30
  • var list2 = list1.AsParallel().WithDegreeOfParallelism(BatchSize).Select(x => x.SomeProcessing()).ToList()
    – adrianm
    Aug 19, 2011 at 14:16

2 Answers 2

3

Q1. How to make batches from list1 and give to threads ?

Parallel.ForEach would be a good start; see MSDN

Q2. How we identify when one tread has finished its operation ?

Parallel.ForEach will handle that; once the ForEach exits, all work is complete

Q3. How we give next item to finished tread ?

Again, Parallel.ForEach handles that

Q4. Will it be cause accessing issues to list2 (since it is accessed by multiple threads) ?

Yes; so either synchronize access (lock etc while adding) , or use a ConcurrentBag<T>

6
  • ForEach will iterate one by one, isn't it ? I need to process multiple items from list1 at the same time, in different threads. Aug 19, 2011 at 7:35
  • @Buddhi no, it won't - Parallel.ForEach - the hint is in the word "Parallel". See MSDN: msdn.microsoft.com/en-us/library/dd992001.aspx Aug 19, 2011 at 7:36
  • Agree ... using Parallel.ForEach will solve your problems without causing you headaches :D
    – Jonathan
    Aug 19, 2011 at 7:39
  • But I am still using .Net ver 2.00 so hope I can't use this... Isn't it ? Aug 19, 2011 at 9:11
  • Or a ConcurrentQueue if he will be needs the stuff in order. Aug 19, 2011 at 9:46
2

You might be looking for the classes in the

System.Collections.Concurrent

namespace.

Microsofts MSDN has listet some articles about list in a multi-threading environment: Parallel programming series You might be looking for the last article of it: Blocking Collection and the Producer-Consumer Problem

There is a longer and specialized article Concurrent Collections in the .NET Framework 4 by Bill Wagner that goes deeper into the topic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.