If You use Task and Thread.CurrentThread inside of the code tree callable from the task’s body You should know something.
The TaskScheduler may decide to run Your tasks on same Thread.
In this case Your code may not work as expected, see sample below:
private Dictionary<Thread, int> uniqueIds = new Dictionary<Thread, int>(); private void InitMyUniqueId(int id) { // thread safety skipped to keep sample simple uniqueIds[Thread.CurrentThread] = id; } public void DoSomething() { // thread safety skipped to keep sample simple var myUniqueId = uniqueIds[Thread.CurrentThread]; Console.Write(myUniqueId); } public void main() { var t1 = new Task(() => { InitMyUniqueId(1); DoSomething(); }); var t2 = new Task(() => { InitMyUniqueId(2); DoSomething(); }); t1.Start(); t2.Start(); }
Depending on TaskScheduler the output can be “12” and “22” too!
The potential impact may be e.g. various context mismatches if You use CurrentThread
to select the local storage slot for Your data, etc. Be careful!
Possible workaround: check Task.CurrentId. If it is not null we are in a task
and using CurrentThread like above is dangerous.