Get a thread id inside parallel.ForEach loop

veda picture veda · Aug 27, 2015 · Viewed 10k times · Source

Is there a way to find the thread id inside Parallel.FoEach loop. I tried using var threadId = Thread.CurrentThread.ManagedThreadId - 1;, but it didn't give me the correct index I was looking for.

Here is an simple example:

private void TestProgram()
    {
        int numThreads = 1;

        var values = new List<float>();
        for (int i = 0; i < numThreads; ++i)
        {
            values.Add(i);
        }

        var data = new List<int>();
        for (int i = 0; i < numThreads; ++i)
        {
            data.Add(i);
        }


        Parallel.ForEach(data, new ParallelOptions{MaxDegreeOfParallelism = numThreads}, i =>
            //foreach (var i in data)
        {
            var threadId = Thread.CurrentThread.ManagedThreadId - 1; // make the index to start from 0

            values[threadId] += i;
        });
    }

Even after setting the MaxDegreeOfParallelism to 1, I still get the threadId to be greater than 1.

Is there a way to find the thread id inside Parallel.ForEach in above scenario?

Note: I could have used Parallel.For in the example I used. But my question is to find it inside Parallel.ForEach

Answer

user957902 picture user957902 · Aug 27, 2015

Since Parallel.ForEach is part of the Task Library, Task.CurrentId will get you closer to what you are looking for:

   var data = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };


   Parallel.ForEach(data, new ParallelOptions { MaxDegreeOfParallelism = 4 }, i =>
   {
            Console.WriteLine(Task.CurrentId);
   });

output is 1 1 1 1 1 1 1 1 1 1 2 2 1

However, there is a disclaimer in the docs:

Task IDs are assigned on-demand and do not necessarily represent the order in which task instances are created. Note that although collisions are very rare, task identifiers are not guaranteed to be unique.