Recursive Function Calls Throw StackOverFlowException

I've to call a function recursively. But after a moment it throws StackOverFlowException. When I used Invoke(new Action(Start)) method, it throws same exception but not in a long moment, this is shorter than the previous one.

How can I overcome this problem?

Example Code:

private void Start()
        {
            // run select query
            mysql(selectQueryString.ToString());
            msdr = mysql();
// is finished
            if (!msdr.HasRows)
            {
                this.Finish();
                return;
            }
            //  get mysql fields
            string[] mysqlFields = Common.GetFields(ref msdr);
            while (msdr.Read())
            {
                // set lastSelectID
                lastSelectID = Convert.ToInt32(msdr[idFieldName].ToString());
                // fill mssql stored procedure parameters
                for (int i = 0; i < matchTable.Count; i++)
                {
                    string valueToAdd = Common.ConvertToEqualivantString(matchTable[i].Type, matchTable[i].Value, ref msdr, ref id, matchTable[i].Parameters);
                    sql.Ekle(matchTable[i].Key, valueToAdd);
                }
                // execute adding operation
                lastInsertID = (int)sql(false);
                // update status bar
                this.UpdateStatusBar();
// update menues
                this.UpdateMenues();
                // increment id for "{id}" statement
                id++;
            }
//  close data reader
            msdr.Close();
            msdr.Dispose();
            mysql.DisposeCommand();
// increment select limit
            selectQueryString.LimitFirst += selectQueryString.LimitLast;
            // call itself until finish
            this.Start();
        }

When the last statement in a function is the call to the function itself, you have tail-recursion. While there are languages that optimize tail-recursion to avoid a stack overflow exception, C# is not one of them.

Recursion is not a good pattern for data that can be of an arbitrary length. Simply replace recursion by a while loop:

private void Start()
{
    while(true) {
        // run select query
        mysql(selectQueryString.ToString());
        msdr = mysql();
        // is finished
        if (!msdr.HasRows)
        {
            this.Finish();
            break;
        }
        //  rest of your code..
    }
}
链接地址: http://www.djcxy.com/p/80614.html

上一篇: 为什么F#编译器不为这个函数创建尾部调用?

下一篇: 递归函数调用抛出StackOverFlowException