2
private int coreCountNum()
    {
        int coreCount = 0;
        foreach (var item in new System.Management.ManagementObjectSearcher("Select NumberOfCores from Win32_Processor").Get())
        {
            coreCount += int.Parse(item["NumberOfCores"].ToString());    
        }
        return coreCount;
    }
private void button1_Click(object sender, EventArgs e)
    {
        coreCount.Text = Convert.ToString(coreCountNum());
    }

This is some of my code which I believe may have an error, if anybody could spot one please let me know. When the button is clicked, it displays the core count on the label but then freezes, thanks.

Luke F
  • 45
  • 6
  • is it freezing when you click on the button? – ivamax9 Dec 29 '16 at 13:11
  • 1
    When you debug which is the line generating the freezing? – NicoRiff Dec 29 '16 at 13:12
  • No, I click the button which works and displayed the correct amount of cores onto the shown label. It's after that when it locks up which is why I thought my loop was naff. – Luke F Dec 29 '16 at 13:13
  • Whatever I do next causes the error, I'm pretty sure I have managed an infinite loop some how. – Luke F Dec 29 '16 at 13:15
  • But that doesn't make sense. If the correct text is shown, the loop is already finished, so this cannot be the freezing code. – René Vogt Dec 29 '16 at 13:15

1 Answers1

0

Try to dispose ManagementObjectSearcher explicitly

private int coreCountNum()
{
    using(var searcher = new System.Management.ManagementObjectSearcher("Select NumberOfCores from Win32_Processor"))
    {
        int coreCount = 0;
        foreach (var item in searcher.Get())
        {
            coreCount += int.Parse(item["NumberOfCores"].ToString());    
        }
        return coreCount;
    }
}
gabba
  • 2,815
  • 2
  • 27
  • 48