Mesut
Mesut

Reputation: 1875

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();
        }

Upvotes: 5

Views: 18209

Answers (2)

negaboys
negaboys

Reputation: 62

You must always have the breaking condition in the recursion. If you need the best sample to implement the recursion in effective way then you can follow this approach recursion example

Upvotes: 0

FarmerBob
FarmerBob

Reputation: 1354

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..
    }
}

Upvotes: 25

Related Questions