Click here to Skip to main content
15,879,326 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to execute same class in windows service using Multi threading.
I have bunch of records and its executed by service multiple times.
I trying various methods but only last thread get executed.

1. Threading
2. parallel Programming
3. var manualResetEventSlim = new ManualResetEventSlim()
4. threads.ForEach(t => t.Start());
5. threads.ForEach(t => t.Join());

only Last thread get executed.
Please help me to sort out the issue.
Thank you in Advance

What I have tried:

List<Thread> threads = new List<Thread>();
foreach (tblFrequencyPeriod Frequency in GetAllProcessing.ToList())
    var manualResetEventSlim = new ManualResetEventSlim();
    cnt += 1;
    int tmp = cnt; // copy value for closure
    Thread t = new Thread(() =>
        ProcessEngine.ProcessEngine objServerLevelProcessing = new ProcessEngine.ProcessEngine();
        objServerLevelProcessing = new SalaryProcessEngine.SalaryProcessEngine(null, "", FrequencyPeriod);
    threads.ForEach(t => t.Start());
    threads.ForEach(t => t.Join());
Updated 21-Feb-20 1:33am

1 solution

Your code seems to be rather confused. It refers to a variable which doesn't exist (FrequencyPeriod). It doesn't use the loop variable (Frequency). It takes a copy of another variable "for closure", but never uses that copy. Each thread waits for a manual reset event which is never set. On each iteration of the loop, you start the current thread, then start all of the threads, then wait for all of the threads to finish.

Try using Parallel.ForEach instead:
Parallel.ForEach(GetAllProcessing.ToList(), frequency =>
    ProcessEngine.ProcessEngine objServerLevelProcessing = new SalaryProcessEngine.SalaryProcessEngine(null, "", frequency);
Parallel.ForEach Method (System.Threading.Tasks) | Microsoft Docs[^]
Write a simple parallel program using Parallel.ForEach | Microsoft Docs[^]
Share this answer
Chaitanya Kulkarni 24-Feb-20 1:04am    
Hi Richard
Thank you for your solution,
but its not working only last record gets executed other than that not works
Can you please suggest any alternative
Richard Deeming 24-Feb-20 3:13am    
Then there's something wrong in the code that you haven't shown us, or in the data which we don't have access to.

You'll need to debug your code to find out what the problem is.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900