-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Description
.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.
winforms/src/System.Windows.Forms/src/System/Windows/Forms/Application.ThreadContext.cs
Lines 513 to 521 in 5bf1bff
| 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.