Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7764975
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T15:03:52+00:00 2026-06-01T15:03:52+00:00

Alright, I have a performancecounter in my program that calculates the CPU usage. It

  • 0

Alright, I have a performancecounter in my program that calculates the CPU usage. It works pretty well, no bugs etc… But! My UI freezes whenever the performancecounter loads.

I load the performancecounter in a backgroundworker so I don’t know why it’s freezing the UI…

Any ideas? If so, thanks!

Code

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        try
        {
            SetPerformanceCounters();
            timerUpdateGUIControls.Start();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }

    private void SetPerformanceCounters()
    {
        performanceCounterCPU.CounterName = "% Processor Time";
        performanceCounterCPU.CategoryName = "Processor";
        performanceCounterCPU.InstanceName = "_Total";

        performanceCounterRAM.CounterName = "% Committed Bytes In Use";
        performanceCounterRAM.CategoryName = "Memory";
    }
    private void timerUpdateGUIControls_Tick(object sender, EventArgs e)
    {
        try
        {
            SystemStatusprogressbarCPU.Value = (int)(performanceCounterCPU.NextValue());
            SystemStatuslabelCPU.Text = "CPU: " + SystemStatusprogressbarCPU.Value.ToString(CultureInfo.InvariantCulture) + "%";

            var phav = PerformanceInfo.GetPhysicalAvailableMemoryInMiB();
            var tot = PerformanceInfo.GetTotalMemoryInMiB();
            var percentFree = ((decimal)phav / tot) * 100;
            var percentOccupied = 100 - percentFree;
            SystemStatuslabelRAM.Text = "RAM: " + (percentOccupied.ToString(CultureInfo.InvariantCulture) + "%").Remove(2, 28);
            SystemStatusprogressbarRAM.Value = Convert.ToInt32((percentOccupied));
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }

The class that gets the RAM value stuffs:

public static class PerformanceInfo
{
    [DllImport("psapi.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetPerformanceInfo([Out] out PerformanceInformation PerformanceInformation,
                                                 [In] int Size);

    [StructLayout(LayoutKind.Sequential)]
    public struct PerformanceInformation
    {
        public int Size;
        public IntPtr CommitTotal;
        public IntPtr CommitLimit;
        public IntPtr CommitPeak;
        public IntPtr PhysicalTotal;
        public IntPtr PhysicalAvailable;
        public IntPtr SystemCache;
        public IntPtr KernelTotal;
        public IntPtr KernelPaged;
        public IntPtr KernelNonPaged;
        public IntPtr PageSize;
        public int HandlesCount;
        public int ProcessCount;
        public int ThreadCount;
    }

    public static Int64 GetPhysicalAvailableMemoryInMiB()
    {
        var pi = new PerformanceInformation();
        if (GetPerformanceInfo(out pi, Marshal.SizeOf(pi)))
        {
            return Convert.ToInt64((pi.PhysicalAvailable.ToInt64() * pi.PageSize.ToInt64() / 1048576));
        }
        return -1;
    }

    public static Int64 GetTotalMemoryInMiB()
    {
        var pi = new PerformanceInformation();
        if (GetPerformanceInfo(out pi, Marshal.SizeOf(pi)))
        {
            return Convert.ToInt64((pi.PhysicalTotal.ToInt64() * pi.PageSize.ToInt64() / 1048576));
        }
        return -1;
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T15:03:53+00:00Added an answer on June 1, 2026 at 3:03 pm

    You create the performance counter in the DoWork of the backgroundworker. But this is only creation and not the actual work. You should move the contents from timerUpdateGUIControls_Tick to backgroundWorker1_DoWork

    struct SystemStatus
    {
        public int CpuLoad;
        public decimal OccupiedPercentage;
    }
    
    private void SetPerformanceCounters()
    {
        performanceCounterCPU.CounterName = "% Processor Time";
        performanceCounterCPU.CategoryName = "Processor";
        performanceCounterCPU.InstanceName = "_Total";
    
        performanceCounterRAM.CounterName = "% Committed Bytes In Use";
        performanceCounterRAM.CategoryName = "Memory";
    }
    
    private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        try
        {
            SetPerformanceCounters();       
    
            while (!backgroundWorker1.CancellationPending)
            {
                SystemStatus status = new SystemStatus();
                status.CpuLoad = (int)(performanceCounterCPU.NextValue())       
    
                var phav = PerformanceInfo.GetPhysicalAvailableMemoryInMiB();
                var tot = PerformanceInfo.GetTotalMemoryInMiB();
                var percentFree = ((decimal)phav / tot) * 100;
                status.OccupiedPercentage = 100 - percentFree;
    
                backgroundWorker1.ReportProgress(0, status);
    
                Thread.Sleep(500); //set update frequency to 500ms
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
    
    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        SystemStatus status = e.UserState as SystemStatus;
    
        SystemStatusprogressbarCPU.Value = status.CpuLoad;
        SystemStatuslabelCPU.Text = "CPU: " + Sstatus.CpuLoad.ToString(CultureInfo.InvariantCulture) + "%";
    
        SystemStatuslabelRAM.Text = "RAM: " + (status.OccupiedPercentage.ToString(CultureInfo.InvariantCulture) + "%").Remove(2, 28);
        SystemStatusprogressbarRAM.Value = Convert.ToInt32(status.OccupiedPercentage);
    }
    

    Don’t forget to add the ProgressChanged function to the backgroundworker1:

    backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Alright I have a question that seems simple but I haven't been able to
Alright I know that the .closest() have been discussed before, but I have been
Alright so I have a task, that I have to let the client try
Alright, I have a server that serves a motion-jpeg stream over http. What I
Hey, alright so I have a .plist that looks like; <plist version=1.0> <dict> <key>Item
Alright lets say I have a cPlayer class that inherits from cOrganism , which
Alright, Question #1: well i have a richtextbox, and id like to add emotions
Alright, I have a wordpress site, that I want to have a clientportal built
Alright I have a div that contains an image, <div id=image> <img src=images/medium/1.png />
Alright, currently I have my SWF hitting a php file that will go and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.