Skip to content

[.NET 7 Preview 2]Sporadic ArgumentException from ThreadLocal initialization #67491

@koszeggy

Description

@koszeggy

Description

My unit tests accidentally revealed an issue in ThreadLocal<T>, more precisely in its IdManager.GetId method:

System.ArgumentException: An item with the same key has already been added. Key: 0
   at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
   at System.Threading.ThreadLocal`1.IdManager.GetId(Boolean trackAllValues)
   at System.Threading.ThreadLocal`1.Initialize(Func`1 valueFactory, Boolean trackAllValues)
   at System.Collections.Concurrent.ConcurrentBag`1..ctor(IEnumerable`1 collection)

Reproduction Steps

I apologize for not being able to provide a minimal repro. I tried to create multiple ConcurrentBag<T> instances in a cycle (as you can see in the call stack the exception comes from its constructor, which initializes a ThreadLocal<int> instance) but I could not reproduce the error this way.

But feel free to fork the Net7Test branch of my repo and execute the tests of the KGySoft.CoreLibraries.UnitTest project.

When executing all of the tests there is a good chance that the SerializeSimpleGenericCollections test case throws the exception with the call stack above. Note that by executing this test alone it will always be green.

Expected behavior

Creating a new ConcurrentBag<T> instance should not throw an exception.

Actual behavior

Creating a new ConcurrentBag<T> may sometimes throw the mentioned exception.

Regression?

No response

Known Workarounds

No response

Configuration

.NET version: 7.0.100-preview.2.22153.17

Other information

No response

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions