C# – Multi-threading in C# .NET Windows Service

cmultithreadingservice

I am writing a Windows Service (using C# .NET 3.5 VS2008) and my requirement is:

  • When the Windows Service start – it performs record check operation (in Database) @ every 30 second interval (I have used a timer for this)

  • If the appropriate record was found in the database – then it starts multiple threads and performs the required operation (that may be network operation or Database operation).

The number of multiple threads also depends on the amount of records found (like if 10 record found then starts 5 threads and for 20 records start 10 threads etc…) How to design/code for these multiple threads?

Example: 10 records found in the database, I want to start 5 threads for first 5 records which may perform network operation… out of 5 threads whichever thread completes his job – will start processing for next the record (i.e Record number 6, 7 … 10)

Please suggest best possible solution for the above case.

Best Answer

I would recommend using Parallel.Net and PLINQ instead of explicit multi-threading. It's easier to manage, is more lightweight and will adapt itself to the numbers of core's you have

Learning resources

http://msdn.microsoft.com/en-us/concurrency/bb895950.aspx

Related Topic