diff --git a/src/TraceEvent/Stacks/Linux/LinuxPerfScriptProcessNameBuilder.cs b/src/TraceEvent/Stacks/Linux/LinuxPerfScriptProcessNameBuilder.cs index 5b9cab66d..5cf195d2a 100644 --- a/src/TraceEvent/Stacks/Linux/LinuxPerfScriptProcessNameBuilder.cs +++ b/src/TraceEvent/Stacks/Linux/LinuxPerfScriptProcessNameBuilder.cs @@ -3,6 +3,7 @@ using System.Diagnostics; using System.Linq; using System.Text; +using System.Threading; namespace Microsoft.Diagnostics.Tracing.StackSources { @@ -16,36 +17,45 @@ internal sealed class LinuxPerfScriptProcessNameBuilder ".NET Server GC" }; + private readonly object _dictionariesLock = new object(); private Dictionary> _candidateProcessNames = new Dictionary>(); private Dictionary _cachedProcessNames = new Dictionary(); private Dictionary _processIds = new Dictionary(); internal void SaveProcessName(StackSourceFrameIndex frameIndex, string processName, int processId) { - if (!_candidateProcessNames.TryGetValue(frameIndex, out HashSet processNames)) + lock (_dictionariesLock) { - processNames = new HashSet(); - _candidateProcessNames.Add(frameIndex, processNames); - } + if (!_candidateProcessNames.TryGetValue(frameIndex, out HashSet processNames)) + { + processNames = new HashSet(); + _candidateProcessNames.Add(frameIndex, processNames); + } - processNames.Add(processName); + processNames.Add(processName); - _processIds[frameIndex] = processId; + _processIds[frameIndex] = processId; + } } internal string GetProcessName(StackSourceFrameIndex frameIndex) { - if (!_cachedProcessNames.TryGetValue(frameIndex, out string processName)) + lock (_dictionariesLock) { - processName = BuildProcessName(frameIndex); - _cachedProcessNames.Add(frameIndex, processName); - } + if (!_cachedProcessNames.TryGetValue(frameIndex, out string processName)) + { + processName = BuildProcessName(frameIndex); + _cachedProcessNames.Add(frameIndex, processName); + } - return processName; + return processName; + } } private string BuildProcessName(StackSourceFrameIndex frameIndex) { + Debug.Assert(Monitor.IsEntered(_dictionariesLock)); + if (_candidateProcessNames.TryGetValue(frameIndex, out HashSet processNames)) { int processId = _processIds[frameIndex];