Skip to content

Application.ThreadContext.FromId reads from s_contextHash while another thread may be writing #13246

@KalleOlaviNiemitalo

Description

@KalleOlaviNiemitalo

.NET version

9.0.3

Did it work in .NET Framework?

Yes

Did it work in any of the earlier releases of .NET Core or .NET 5+?

I guess it would have worked in .NET 7, because #8161 was not merged there.

Issue description

The Application.ThreadContext.FromId method reads from the s_contextHash dictionary without locking. This can cause an error if another thread writes to the dictionary at the same time.

internal static ThreadContext? FromId(uint id)
{
if (!s_contextHash.TryGetValue(id, out ThreadContext? context) && id == PInvoke.GetCurrentThreadId())
{
context = Create();
}
return context;
}

Writers do lock (s_tcInternalSyncObject) but this reader doesn't. AFAICT, the callers of Application.ThreadContext.FromId don't lock it either.

Before #8161, s_contextHash used to be a Hashtable, which is safe for one writer in parallel with multiple readers. Dictionary<TKey, TValue> is not safe for that use.

Steps to reproduce

Found by source code inspection, not reproduced.

Metadata

Metadata

Labels

Type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions