Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ManagedThreadID is not unique?

My program creates some threads for some tasks.

My code is like this:

Dictionary<int, double> threadStates = new Dictionary<int, double>();
for (int i = 0; i < SubNNs.Count(); i++)
{
    Thread tt = new Thread(StartTrainingSubs);
    threadStates.Add(tt.ManagedThreadId, 0);
    tt.Priority = ThreadPriority.Highest;
    tt.Start(i);
}

But sometimes, if SubNNs.Count() becomes large (10-20), The program throws this exception : "An item with the same key has already been added." at line threadStates.Add(tt.ManagedThreadId, 0);

Why I giving this error? Isn't ManagedThreadId unique? If yes, what should I do?

and If no, maybe a thread finishes and another thread starts with same ManagedThreadId? Is it possible? how to prevent this problem?

Or there is another problem?

EDIT : Users said that ManagedThreadId can be reused. So, since in later parts of code, each thread needs to know itself with a unique number, is there any way to add something like a name to thread that every thread can get its unique number?

Thanks for any advise!

like image 291
Mahdi Ghiasi Avatar asked Dec 21 '11 21:12

Mahdi Ghiasi


People also ask

Is ManagedThreadId unique?

A thread's ManagedThreadId property value serves to uniquely identify that thread within its process. The value of the ManagedThreadId property does not vary over time, even if unmanaged code that hosts the common language runtime implements the thread as a fiber.

What can be used as a unique identifier of a thread?

The getid() function from the Thread class is used to extract a unique thread ID. This unique identifier is assigned when we create a new thread in our program.

What is thread ID in C#?

It allows creating and accessing individual threads in a multithreaded application. The first thread to be executed in a process is called the main thread. When a C# program starts execution, the main thread is automatically created.


1 Answers

If no, maybe a thread finishes and another thread starts with same ManagedThreadId? Is it possible? how to prevent this problem?

Yes. Managed thread IDs can be reused. They are not a good choice for a dictionary state key.

Instead of using the thread ID to track state, you should consider using some other unique value. In your case, "i" is unique per loop - why not use it as your key?

like image 128
Reed Copsey Avatar answered Oct 22 '22 15:10

Reed Copsey