Search code examples
c#stack-overflowhresultunhandledhttpunhandledexception

StackOverflowException was unhandled HResult=-2147023895


public void serialcek()
    {

            while (!exitThread)
            {
                foreach (ManagementObject currentObject in theSearcher.Get())
                {

                    try
                    {
                        textBox1.Text = currentObject["Size"].ToString() + " " + currentObject["PNPDeviceID"].ToString();
                        currentObject.Dispose();

                    }
                    catch (Exception)
                    {
                        //    MessageBox.Show("Bişiler oldu bende anlamadım");
                        currentObject.Dispose();
                        //exitThread = false;
                    }
                }

            }
            Thread.Sleep(100);
            serialcek();
        }

i use thread. but its a few minute later an error. click button is exitThread make true. than 5 min later give an StackOverflowException was unhandled HResult=-2147023895 error.

thanks for help.


Solution

  • Your calling serialcek() recursivly without stopping and by that causing a stack overflow.

    P.s. use finally with try\catch to prevent code duplication:

    public void serialcek()
    {
    
            while (!exitThread)
            {
                foreach (ManagementObject currentObject in theSearcher.Get())
                {
                    try
                    {
                        textBox1.Text = currentObject["Size"].ToString() + " " + currentObject["PNPDeviceID"].ToString();
                    }
                    catch (Exception)
                    {
                        // MessageBox.Show("Bişiler oldu bende anlamadım");
                        //exitThread = false;
                    }
                    finally
                    {
                       currentObject.Dispose();
                    }
                }
            }
            Thread.Sleep(100);
    
            if(<condition>) // add your condition here
            {
               serialcek();
            }
        }