Chiritescu Adrian Chiritescu Adrian - 26 days ago 10
C# Question

How to reuse a method while it is still running?

I have the following code:

CreateMultiLayerWakeupSteps()
{
var wakeupStep = new AutodetectWakeupStep
{
//Creating the object...
}

//Later in the process I have this operation:

wakeupStep.SuccessNextStep = UserInputs(wakeupStep);
}


The UserInputs method implementation looks something like this:

private static AutodetectCommandStep UserInputs(AutodetectWakeupStep wakeupStep)
{
AutodetectCommandStep autodetectCommandStep
{
//Creating the object...
}

//Some more operations autodetectCommandStep here...

return autodetectCommandStep;
}


In the UserInputs method I would like to call the CreateMultiLayerWakeupStep method again in order to create a new step but the following exception is thrown: StackOverflowException.

Is there a solution to reuse the method while still running ? It is difficult to implement ? I am not familiar with threading asynchronization.

Best regards !

Answer

There is nothing about multithreading here. You are trying to make a recursion, but you don't specify when the recursion will end. Because of that you receive StackOverflowException.

So for example you should have a property in AutodetectCommandStep.ExecuteAgain

void CreateMultiLayerWakeupSteps()
{
    var wakeupStep = new AutodetectWakeupStep
    {
        //Creating the object...
    }

    //Later in the process I have this operation:

    wakeupStep.SuccessNextStep = UserInputs(wakeupStep);

    if(wakeupStep.SuccessNextStep.ExecuteAgain)
        CreateMultiLayerWakeupSteps();
}

You should decide when this ExecuteAgain will be false depending on your context so you will leave the method. If it is always true, it will throw same exception.

Also probably a good idea is to create the AutodetectWakeupStep object outside the CreateMultiLayerWakeupSteps(AutodetectWakeupStep wakeUpStep). And your code will look like this.

void CreateMultiLayerWakeupSteps(AutodetectWakeupStep wakeUpStep)
{

      AutodetectWakeupStep step = UserInputs(wakeupStep);

      if(step.ExecuteAgain)
           CreateMultiLayerWakeupSteps(step);
}
Comments