These are local variables, they exist independently of each other and the compiler and the runtime will never mix them up because they are... local to where they were declared. In fact, local variables are not a concern for threading, see Thread safety and local variables [*].
Once compiled, the name of local variables is lost (they will be - the equivalent of saying - local variable 1
, local variable 2
, etc...). That is, in Microsoft Intermediate Language, the name of local variables is irrelevant. See OpCodes.Ldloc Field.
Will it cause the threads to slow down because they are using the same variable?
No. These are unfounded worries. These local variables have nothing to do with each other.
Or will it cause the wrong values to be shown at the UI since the value is always changing?
This could happen regardless of variables names. What matters is what value you show in UI, and when and where you show it. What was the name of the variable holding it has no impact.
My program will have a lot of threads so I worry about the potential unforeseen consequences.
Worry not about local variables. Once we start talking about some form of shared memory across threads then you have a reason to worry. And no, local variables are not shared across threads, let me be clear here: they are local [**].
I want to suggest Joseph Albahari's series Threading in C#. Which despite being outdated [***] are well written, have clear examples, and get all the fundamentals across.
With that said, naming variables is important for readability and maintainability of the code. Anyway, I am not in the mood to preach. So, you do you. I will only say on the matter this: the next time you see a variable and you are not sure what it is or where else you might be using it, think about it.
[*]: The answer to the linked question mentions two ways a local variable could be exposed. Both amount to upgrade the local variable to a field of ana nonymous object behind the scenes (yield return
copies the value to a hidden IEnumerator
, on the other hand if make a closure on a local variable and share it, you are sharing the local variable - in a hidden anonymous class).
[**]: Even if you are using async/await
and the method was resumed in a different thread, there is no chance two threads will share the local variable (it changed hands, but you usually have no reason to worry about that, unless you are using ThreadLocal
or similar).
[***]: these days we will be using async/await
, in fact, why are you using BackgroundWorker
?