Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# threading question

My existing c# app updates a sharepoint site collection. Now I've been task to make my c# app update not 1 but 15 site collections. It would take too long to run sequentially, so threading would be a good solution.

However I can't just open 15 threads at once, I would like to have a configurable value which will be the max number of threads to run at once.

What I would expect is:

  • Define Max_Threads variable...
  • Assign a queue of tasks (functions) at the thread pool, in this case 15 tasks or function calls.
  • The thread pool then executes each thread, however is limited by how many open threads (5 for example).
  • Once a thread completes, the threadpool then reuses that thread to do another item of work, until all the work is complete.

So my question is: Is all this build into .net threading. Or do I have to manually create the thread management code?

EDIT: this is a framework 3.5 project, sorry for not mentioning this before.

like image 221
JL. Avatar asked Dec 27 '22 13:12

JL.


2 Answers

just use Tasks and don't think about the thread-numbers. The TPL will do all this for you.

like image 188
Random Dev Avatar answered Dec 30 '22 02:12

Random Dev


The book C# in a Nutshell, 4.0, (by Albahari & Albahari) gives a neat example of simultaneously calling many "web clients" and downloading information. It uses PLINQ, does it in one or so lines of code. The PLINQ library handles the creation of the threads, etc. If you look at it, it doesn't tend to make too many threads, although you can force a limit of the maximum number of threads at a time. Similarly, you can use the Parallel.Foreach() and use the "ParallelOptions" parameter to limit the number of threads.

The nice thing is that you never have to create the threads yourself - it's automatic. And it does a fine job of load balancing.

A good tutorial is http://www.albahari.com/threading/ - look at Part 5 on Parallel Programming for lots of examples of using PLINQ and Parallel.Foreach.

Also, the Wagner book on Effective C# (4.0) has similar examples.

like image 30
Marc Meketon Avatar answered Dec 30 '22 02:12

Marc Meketon