如何在方法仍在运行时重用该方法?

时间:2016-11-07 14:48:35

标签: c# multithreading async-await

我有以下代码:

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

    //Later in the process I have this operation:

    wakeupStep.SuccessNextStep = UserInputs(wakeupStep);
}

UserInputs 方法实现如下所示:

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

        //Some more operations autodetectCommandStep here...

        return autodetectCommandStep;
    }

UserInputs 方法中,我想再次调用 CreateMultiLayerWakeupStep 方法以创建新步骤,但抛出以下异常: StackOverflowException

是否有解决方案在仍在运行时重用该方法?难以实施?我不熟悉线程异步。

祝你好运!

1 个答案:

答案 0 :(得分:3)

这里没有关于多线程的信息。您正在尝试进行递归,但是您没有指定递归何时结束。因此,您收到StackOverflowException

例如,您应该在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();
}

根据您的情况,您应该决定此ExecuteAgain何时为假,这样您就可以离开该方法了。如果它总是为真,它将抛出相同的异常。

也许一个好主意是在CreateMultiLayerWakeupSteps(AutodetectWakeupStep wakeUpStep)之外创建AutodetectWakeupStep对象。你的代码看起来像这样。

void CreateMultiLayerWakeupSteps(AutodetectWakeupStep wakeUpStep)
{

      AutodetectWakeupStep step = UserInputs(wakeupStep);

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