How to use Task.CallRoutine()?

I have developed a FlexPendant GUI application. I can get/set persistent values, inputs and outputs. But I cannot get Task.CallRoutine() to work however. Every time I call it, I get the error “SYS_E_EXEC_LEVEL: Operation is illegal at current execution level” or “[SDK.Rapid.CallRoutine] a task is executing”.
I tried it in the foreground task, in a background task, in auto mode and manual mode but I cannot get it to work.
How do I use the Task.CallRoutine() function (if possible in a background task)?

Thanks.

The task which contains the routine, must be in “STOP” state, meaning that the program-pointer is set and the task is not executing.

If the program-pointer is not set, the error “SYS_E_EXEC_LEVEL: Operation is illegal at current execution level” will be thrown.

If the task is running, the error “[SDK.Rapid.CallRoutine] a task is executing” will be thrown.

So means you have to check in your FP-application what the state is of the task, for example this:

  PROC TestRoutine()
    ! Write message to TP
    TPWrite "TestRoutine executed...";
    
    ! Terminate program -> loose program-poiner
    Exit;
  ENDPROC


private void button2_Click(object sender, EventArgs e)
{
    //Declare Variables
    Task tRob1 = null;
    Controller RobotController = null;
    StartResult sRes;

    try
    {
        //Get RobotController
        RobotController = new Controller();

        //Get Task
        tRob1 = RobotController.Rapid.GetTask("T_ROB1");

        //Check task-state
        if (tRob1.ExecutionState == ExecutionState.Started)
        {
            // Cannot call routine, because task already running
            GTPUMessageBox.Show(this, null, "Task running...\n Stop execution and try again...", null);
        }
        else
        {
            //When state is ready, the PP is not set -> reset PP
            if (tRob1.ExecutionState == ExecutionState.Ready)
            {
                tRob1.ResetProgramPointer();
            }

            // Call the TestRoutine
            sRes = tRob1.CallRoutine("TestRoutine");
            GTPUMessageBox.Show(this, null, "Call result...\n" + sRes.ToString(), null);
        }
    }
    catch (Exception ex)
    {
        // Exception handling
        GTPUMessageBox.Show(this, null, "Error...\n" + ex.Message, null);
    }
    finally
    {
        // clean-up task
        if (tRob1 != null)
        {
            tRob1.Dispose();
            tRob1 = null;
        }

        // clean-up controller
        if (RobotController != null)
        {
            RobotController.Dispose();
            RobotController = null;
        }
    }
}