title: Why is this code sending a cross thread operation exception?
body: <p>I've been attempting to implement a CPU monitor that updates every two seconds and displays it on a label called &quot;cpu_usage&quot; in WinForms. Unfortunately my code does not appear to work and gives off this error during runtime:</p>
  <pre><code> System.InvalidOperationException: 'Cross-thread operation not valid: Control 'cpu_usage' accessed from a thread other than the thread it was created on.'
  </code></pre>
  <p>So far I've done a little bit of debugging, and have out that the error occurs whenever I try to display the percentage on the &quot;cpu-usage&quot; label, but I am still unable to figure out how to fix this issue. The CPU monitoring code is below:</p>
  <pre><code>    public my_form()
      {
          InitializeComponent();
  
          // Loads the CPU monitor
          cpuCounter = new PerformanceCounter();
          cpuCounter.CategoryName = &quot;Processor&quot;;
          cpuCounter.CounterName = &quot;% Processor Time&quot;;
          cpuCounter.InstanceName = &quot;_Total&quot;;
          InitTimer();
      }
  
      // Timer for the CPU percentage check routine
      public void InitTimer()
      {
          cpu_timer = new Timer();
          cpu_timer.Elapsed += new ElapsedEventHandler(cpu_timer_Tick);
          cpu_timer.Interval = 2000;
          cpu_timer.Start();
      }
  
      // Initates the checking routine
      private void cpu_timer_Tick(object sender, EventArgs e)
      {
          cpu_usage.Text = getCurrentCpuUsage(); // This line causes the exception error.
      }
  
      // Method to find the CPU resources
      public string getCurrentCpuUsage()
      {
          string value1 = (int)cpuCounter.NextValue() + &quot;%&quot;;
          Thread.Sleep(500);
          string value2 = (int)cpuCounter.NextValue() + &quot;%&quot;;
          return value2.ToString();
      }
  </code></pre>