My code puts 10 'jobs' in a queue, displays their thread IDs, and start running right away and in parallel. I know the jobs are running in parallel since each job is simply a 20 second delay, and all 10 jobs complete in 20 seconds. What perplexes me is that there are several duplicate ThreadIDs, and supposedly each thread should have a unique ID from what I have read. How is this possible? Are there duplicates because the duplicates could be on different processor cores (if so this would not be great as eventually I want to be able to cancel a task using its thread ID) ?
Here's a list of the thread IDs that were shown on my console window"
Thread ID: 10 Thread ID: 11 Thread ID: 11 Thread ID: 12 Thread ID: 13 Thread ID: 14 Thread ID: 15 Thread ID: 16 Thread ID: 6 Thread ID: 6
I simplified the code as much as I could, and timed how long it took the program to finish.
This is a console app
class Program
{
private static Object lockObj = new Object();
static void Main(string[] args)
{
var q = new TPLDataflowMultipleHandlers();
var numbers = Enumerable.Range(1, 10);
Console.Clear();
foreach (var num in numbers)
{
q.Enqueue(num.ToString());
}
Console.ReadLine();
}
} // end of program class
public class TPLDataflowMultipleHandlers
{
private static Object lockObj = new Object();
private ActionBlock<string> _jobs;
public TPLDataflowMultipleHandlers()
{
var executionDataflowBlockOptions = new ExecutionDataflowBlockOptions()
{
MaxDegreeOfParallelism = 16,
};
_jobs = new ActionBlock<string>(async (job) =>
{
ShowThreadInformation("Main Task(Task #" + Task.CurrentId.ToString() + ")");
Console.WriteLine($"STARTING job:{job}, thread: { Thread.CurrentThread.ManagedThreadId}");
await Task.Delay(20000);
Console.WriteLine($"FINISHED job:{job}, thread: { Thread.CurrentThread.ManagedThreadId}");
}, executionDataflowBlockOptions);
}
public void Enqueue(string job)
{
_jobs.Post(job);
}
private static void ShowThreadInformation(String taskName)
{
String msg = null;
Thread thread = Thread.CurrentThread;
lock (lockObj)
{
msg = String.Format("{0} thread information\n", taskName) +
String.Format(" Background: {0}\n", thread.IsBackground) +
String.Format(" Thread Pool: {0}\n", thread.IsThreadPoolThread) +
String.Format(" Thread ID: {0}\n", thread.ManagedThreadId);
}
Console.WriteLine(msg);
}
}
I was fully expecting 10 unique thread ID numbers.