c#高度使用的内存。 for ManagementObjectSearcher

时间:2014-07-27 13:29:54

标签: c# multithreading usb

private void Form1_Load(object sender, EventArgs e)
{

    t = new Thread(new ThreadStart(serialcek));
    CheckForIllegalCrossThreadCalls = false;
    t.Start();
  }

public void serialcek()
{

    ManagementObjectSearcher theSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'");
    try
    {
        foreach (ManagementObject currentObject in theSearcher.Get())
        {
            ManagementObject theSerialNumberObjectQuery = new ManagementObject("Win32_PhysicalMedia.Tag='" + currentObject["DeviceID"] + "'");
            try
            {
                serial = theSerialNumberObjectQuery["SerialNumber"].ToString();
                textBox1.Text = serial;
            }
            catch (Exception)
            {
                // MessageBox.Show("Bişiler oldu bende anlamadım");

            }

        }
        Thread.Sleep(sure);
        serialcek();
    }
    catch (Exception ex)
    {
        MessageBox.Show("Patladım ben." + ex.Message.ToString());
    }

}

使用线程。但我无法阻止它。线程始终运行,应用程序使用内存高。 几分钟后发出错误。也许我不能用于功能真实。

1 个答案:

答案 0 :(得分:2)

这是因为你在没有任何退出条件的情况下递归调用线程的方法。这最终将导致StackOverflowException

您应该在线程的方法中放置一个while循环,而不是这种方法。 这当然是大致实施的,只是为了给你一个想法:

bool exitThread;

private void Form1_Load(object sender, EventArgs e)
{

    t = new Thread(new ThreadStart(serialcek));
    CheckForIllegalCrossThreadCalls = false;
    exitThread = false;
    t.Start();
  }

public void serialcek()
{

    ManagementObjectSearcher theSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'");
    while (! exitThread)
    {
        try
        {
            foreach (ManagementObject currentObject in theSearcher.Get())
            {
                ManagementObject theSerialNumberObjectQuery = new ManagementObject("Win32_PhysicalMedia.Tag='" + currentObject["DeviceID"] + "'");
                try
                {
                    serial = theSerialNumberObjectQuery["SerialNumber"].ToString();
                    textBox1.Text = serial;
                }
                catch (Exception)
                {
                    // MessageBox.Show("Bişiler oldu bende anlamadım");

                }

            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Patladım ben." + ex.Message.ToString());
        }
        finally
        {
            // Moved Sleep into 'finally' block to make it be called even if an exception occurs
            Thread.Sleep(sure);
    }    
}

然后您可以随时退出此主题,只需将true分配给exitThread

private void Button1_Click(object sender, EventArgs e)
{
    exitThread = true;
}