Click here to Skip to main content
15,917,964 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
How can i know whether threads created by Parallel.Foreach are still running or not?

Because if any one of the threads are still running, then i need to do some operation.

The below code might be help

C#
Parallel.ForEach(GetProcess(), ExecuteProcess);

public IEnumerable<lucent.spat3g.dsm.bllcommon.processmodule> GetProcess()
        {
            Lucent.SPAT3G.DSM.BLLCommon.ProcessModule process = null;
            while (true)
            {
                process = _DDMatrix.GetReadyProcess();
                if (process == null)
                {
                    if (RunningProcessCount == 0)
                    {
                        Logger.Write("no process is ready AND no process is running.hence, processing over", QdalDsmConstants.LOGGER_CATEGORY_BLL);
                        break;
                    }
                    else
                        continue;
                }

                yield return process;
            }
        }

private void ExecuteProcess(Lucent.SPAT3G.DSM.BLLCommon.ProcessModule process)
        {
            // update jobtime
            RunningProcessCount++;
            CommonRegistryQuery regQuery = new CommonRegistryQuery();
            regQuery.WriteRegistry(Registry.LocalMachine, QdalDsmConstants.REG_KEY_DSM_BASE, QdalDsmConstants.REG_VAL_DSM_JOB_TIME, DateTime.Now.ToString("yyyyMMddhhmmss"));

            Logger.Write("launching process on thread 1: " + process.Id, QdalDsmConstants.LOGGER_CATEGORY_BLL);
            _DDMatrix.UpdateProcessStatus(process.Id, ProcessStatus.Running);
            PECommonWrap processWrap = new PECommonWrap(_DSMConfig, _SprMeta, _QidConfig, process);

            try
            {
                Logger.Write("Executing process " + process.Id, QdalDsmConstants.LOGGER_CATEGORY_BLL);
                bool result = ExecuteProcess(processWrap);
                if (result)
                {
                    _DDMatrix.UpdateProcessStatus(process.Id, ProcessStatus.Done);
                    Logger.Write("Process " + process.Id + " completed successfully", QdalDsmConstants.LOGGER_CATEGORY_BLL);
                }
                else
                {
                    _DDMatrix.UpdateProcessStatus(process.Id, ProcessStatus.Error);
                    Logger.Write("Process " + process.Id + " completed unsuccessfully", QdalDsmConstants.LOGGER_CATEGORY_BLL_ERROR);
                }
            }
            catch (Exception ex)
            {
                Logger.Write("failed in bwProcess1_DoWork, e:" + ex.Message, QdalDsmConstants.LOGGER_CATEGORY_BLL_ERROR);
                _DDMatrix.UpdateProcessStatus(process.Id, ProcessStatus.Error);
            }

            Logger.Write("runworker compeleted", QdalDsmConstants.LOGGER_CATEGORY_BLL);
            // update available file status
            _DDMatrix.UpdateFileStatus(new DirectoryInfo(_DSMConfig.WorkAreaDataIn.ToString()));
            _DDMatrix.UpdateFileStatus(new DirectoryInfo(_DSMConfig.WorkAreaDataOut.ToString()));
            RunningProcessCount--;
        }


Now im controlling manually by keeping the one variable called RunningProcessCount, Is there any way yo know that any of the threads that belongs to Parallel.Foreach is still running?

Thanks inadvance

Hari

[edit]Code block added - OriginalGriff[/edit]
Posted
Updated 20-Jun-12 21:51pm
v2

You can use any collection to get a list of your running threads.
For simplicity here I used a string. But you could use a list of your own objects.

C#
string RunningThreads = string.Empty;
object LockObject = new Object();

Parallel.ForEach("ABCDEFGHIJKLMNOP", (c, i) =>
{
    lock (LockObject)
    {
        RunningThreads += c.ToString();
        System.Console.WriteLine("Starting thread " + c+ ". Running threads: " + RunningThreads);
    }

    Thread.Sleep(1000);

    lock (LockObject)
    {
        RunningThreads = RunningThreads.Replace(c.ToString(), "");
        System.Console.WriteLine("Ending thread   " + c + ". Running threads: " + RunningThreads);
    }
});
System.Console.WriteLine("The End");
System.Console.WriteLine("Running threads: " + RunningThreads + " (should be empty)");

Output
CSS
Starting thread A. Running threads: A
Starting thread B. Running threads: AB
Starting thread C. Running threads: ABC
Starting thread D. Running threads: ABCD
Starting thread E. Running threads: ABCDE
Ending thread   A. Running threads: BCDE
Starting thread F. Running threads: BCDEF
Ending thread   B. Running threads: CDEF
Starting thread G. Running threads: CDEFG
Ending thread   C. Running threads: DEFG
Starting thread H. Running threads: DEFGH
Ending thread   D. Running threads: EFGH
Starting thread I. Running threads: EFGHI
Ending thread   E. Running threads: FGHI
Starting thread J. Running threads: FGHIJ
Starting thread K. Running threads: FGHIJK
Ending thread   F. Running threads: GHIJK
Starting thread L. Running threads: GHIJKL
Ending thread   G. Running threads: HIJKL
Ending thread   H. Running threads: IJKL
Starting thread N. Running threads: IJKLN
Starting thread M. Running threads: IJKLNM
Ending thread   I. Running threads: JKLNM
Starting thread O. Running threads: JKLNMO
Ending thread   J. Running threads: KLNMO
Starting thread P. Running threads: KLNMOP
Ending thread   K. Running threads: LNMOP
Ending thread   L. Running threads: NMOP
Ending thread   N. Running threads: MOP
Ending thread   M. Running threads: OP
Ending thread   P. Running threads: O
Ending thread   O. Running threads:
The End
Running threads:  (should be empty)
 
Share this answer
 
Comments
yeshgowda 22-Jun-12 0:24am    
Good answer .My 5!
Sergey Alexandrovich Kryukov 16-Nov-12 22:52pm    
I don't think what you show are really threads. Parallel mechanism is based on threads but abstracted from them. And what OP wants just makes no practical sense. The whole idea is to hide threads from the developer.

But it's of course interesting to experiment with parallels and see how tasks are dispatched to threads. Right approach would be taking CurrentThread, ManagerThreadId if it, and comparing them...

Got the idea?

--SA
The Paraller.ForEach method waits till all the children threads complete.
In the code below 'The End' will only appear when all the ForEach functions have been completed.
C#
Parallel.ForEach("ABC", (c) =>
{
    Console.WriteLine("Starting " + c);
    Thread.Sleep(1000);
    Console.WriteLine("Ending " + c);
});
Console.WriteLine("The End");

Output:
Starting A
Starting C
Starting B
Ending C
Ending A
Ending B
The End

Am I missing something?
 
Share this answer
 
v2
Comments
HariPrasadbrk 21-Jun-12 7:55am    
Hi Pascal,
Thank you very much, what ever you are telling is correct. But my requirement is not this. Mine is different, is there a way to get any child threads that is created by Parallel.Foreach are still running or not..

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


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