简体   繁体   中英

Why are my ThreadIDs not unique for 10 tasks running in parallel?

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.

Threads and Tasks are not the same things - think of a Thread as a worker, and a Task as a piece of work to be performed. Just because you created 10 things that need to be done doesn't mean that you need 10 workers to do them - it would be much more efficient if, say, the 4 workers you already have (the default amount of worker threads in the .NET ThreadPool ) started executing the work units, and new workers ( Threads ) would be created only if the existing ones don't seem to keep up. Each "work unit" you created in your code is very short, and so it gets executed very quickly and the same thread that performed it becomes free and runs another one that was waiting in a queue in the background.

If you want to see this in action, just place something like Thread.Sleep(30000) somewhere in your ShowThreadInformation . This will cause the execution of your tasks to be artificially long, and the .NET thread pool will notice tasks are being starved in the queue and spin up new threads to execute them.

Take a look here - What is the difference between task and thread?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM