Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PerformanceCounter implementation is taking large memory allocation #1694

Closed
reyang opened this issue Feb 19, 2020 · 0 comments
Closed

PerformanceCounter implementation is taking large memory allocation #1694

reyang opened this issue Feb 19, 2020 · 0 comments
Milestone

Comments

@reyang
Copy link
Member

reyang commented Feb 19, 2020

The following code is causing large memory allocation:

return pid == (int)new PerformanceCounter(categoryName, counterName, i, true).RawValue;

Suggested improvement:

        static readonly ConcurrentDictionary<string, Tuple<DateTime, PerformanceCounterCategory, InstanceDataCollectionCollection>> cache = new ConcurrentDictionary<string, Tuple<DateTime, PerformanceCounterCategory, InstanceDataCollectionCollection>>();

        private static string FindProcessInstance1(int pid, IEnumerable<string> instances, string categoryName, string counterName)
        {
            Tuple<DateTime, PerformanceCounterCategory, InstanceDataCollectionCollection> cached;

            DateTime utcNow = DateTime.UtcNow;

            InstanceDataCollectionCollection result = null;

            PerformanceCounterCategory category = null;

            if (cache.TryGetValue(categoryName, out cached))
            {
                category = cached.Item2;

                if (cached.Item1 < utcNow)
                {
                    result = cached.Item3;
                }
            }

            if (result == null)
            {
                if (category == null)
                {
                    category = new PerformanceCounterCategory(categoryName);
                }

                result = category.ReadCategory();

                cache.TryAdd(categoryName, new Tuple<DateTime, PerformanceCounterCategory, InstanceDataCollectionCollection>(utcNow.AddMinutes(1), category, result));
            }

            InstanceDataCollection counters = result[counterName];

            if (counters != null)
            {
                foreach (string i in instances)
                {
                    InstanceData instance = counters[i];

                    if ((instance != null) && (pid == instance.RawValue))
                    {
                        return i;
                    }
                }
            }

            return null;
        }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants