locked
Program Crashes on pressing Close RRS feed

  • Question

  • Hi Guys, my program crashes whenever i press close on it, always at the same part with the following error:

    System.InvalidOperationException was unhandled
      Message=Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
      Source=System.Windows.Forms
      StackTrace:
           at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
           at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
           at System.Windows.Forms.Control.Invoke(Delegate method)
           at ClientSendOnTimedEvent.frmMain.PerfCounters() in D:\My Documents\Visual Studio 2010\Projects\ClientSendOnTimedEvent\ClientSendOnTimedEvent\frmMain.cs:line 56
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()
      InnerException:

     

    Here's the code for it, with the bit it selects highlighted in bold:

     

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Threading;
    using System.Diagnostics;
    using System.Management;


    namespace ClientSendOnTimedEvent
    {
        public partial class frmMain : Form
        {
            public frmMain()
            {
                InitializeComponent();
            }

            public void frmMain_Load(object sender, EventArgs e)
            {
                Thread thrdPerformaceCounters = new Thread(PerfCounters);
                thrdPerformaceCounters.Start();
            }

            public void PerfCounters()
            {
                while (true)
                {
                    PerformanceCounter CounterCPU;
                    PerformanceCounter CounterMemory;
                    float Cpu;
                    float Ram;
                    string CpuPercentage;
                    string RamAvailable;

                    CounterCPU = new PerformanceCounter("Processor", "% User Time");
                    CounterCPU.InstanceName = "_Total";

                    CounterMemory = new PerformanceCounter("Memory", "Available MBytes");

                    Cpu = CounterCPU.NextValue();
                    Ram = CounterMemory.NextValue();

                    Thread.Sleep(1000);

                    Cpu = CounterCPU.NextValue();
                    Ram = CounterMemory.NextValue();

                    CpuPercentage = Cpu.ToString("N1");
                    RamAvailable = Ram.ToString();

                    this.Invoke((MethodInvoker)delegate()
                    {
                        txtCpuPerc.Text = CpuPercentage + "%";
                        txtRamAvailable.Text = RamAvailable + "MB";
                        //txtHddPerc.Text = strHddPerc + "%";
                        //txtSystemPerc.Text = (dblCalcSystemPerc.ToString("N1") + "%");
                        //txtRamPerc.Text = (dblTotalRamPerc.ToString("N1") + "%");
                        //txtUsedRamPerc.Text = (dblUsedRamPerc.ToString("N1") + "%");
                    });
                }
            }

        }
    }

    Any help/thoughts regarding this will be most helpful! Thanks guys

    • Moved by CoolDadTx Monday, January 23, 2012 12:16 AM Winforms related (From:Visual C# General)
    Sunday, January 22, 2012 10:02 PM

Answers

  • The problem is that PerfCounter contains a method that never exits. If you close the application during this task, the form will be destroyed, but the thread remains alive, so, when it runs the Invoke method, the UI isn't available, and then you obtain the error.

    To solve the problem, add the following line before starting the thread:

    thrdPerformaceCounters.IsBackground = true;
    

    In this way, the thread is configured as a background thread, then it is automatically terminates then the main thread stops.


    Marco Minerva [MCPD]
    Blog: http://blogs.ugidotnet.org/marcom
    Twitter: @marcominerva
    • Marked as answer by Twin Givings Monday, January 23, 2012 9:14 AM
    Sunday, January 22, 2012 11:55 PM

All replies

  • You need to close the thread in a form closing event handler.  The error comes from the thread still trying to update controls that are closed.

    --
    Mike
    Sunday, January 22, 2012 11:54 PM
  • The problem is that PerfCounter contains a method that never exits. If you close the application during this task, the form will be destroyed, but the thread remains alive, so, when it runs the Invoke method, the UI isn't available, and then you obtain the error.

    To solve the problem, add the following line before starting the thread:

    thrdPerformaceCounters.IsBackground = true;
    

    In this way, the thread is configured as a background thread, then it is automatically terminates then the main thread stops.


    Marco Minerva [MCPD]
    Blog: http://blogs.ugidotnet.org/marcom
    Twitter: @marcominerva
    • Marked as answer by Twin Givings Monday, January 23, 2012 9:14 AM
    Sunday, January 22, 2012 11:55 PM