Threads, Synchronization and Thread Safety
SyncLock (Monitor) Mutual exclusion within a process Atomic numeric operations Many readers, few writers
Limit concurrency. Async-friendly (WaitAsync).
Mutex (named) Cross-process (single-instance apps) ManualResetEventSlim / AutoResetEvent / CountdownEvent / Barrier Lazy(Of T) / LazyInitializer Thread-safe lazy initialization
ThreadLocal(Of T) / <ThreadStatic> / AsyncLocal(Of T) Per-thread / per-async-flow data Concurrent* collections, ImmutableX Thread-safe data structures
Thread-safety strategies: immutability, confinement (one owner), synchronization, message passing.
Deadlock avoidance: consistent lock ordering, minimal lock scope, no awaiting inside SyncLock (it isn't allowed), use SemaphoreSlim for async critical sections.
UI thread affinity: WinForms Control.Invoke/BeginInvoke, WPF Dispatcher.Invoke, or SynchronizationContext.Post.
Imports System.Threading
Public Class SafeCounter
Private ReadOnly _gate As New Object()
Private _count As Integer
Public Sub Increment()
SyncLock _gate
_count += 1
End SyncLock
End Sub
Public ReadOnly Property Count As Integer
Get
Return Volatile.Read(_count)
End Get
End Property
End Class
Interlocked.Increment(_hits)
Interlocked.CompareExchange(_state, newValue, expected)