Wrapper invalid problem

After generate the path in code,I begin the simulation in vc which is no problem.But I start the simulation in code,the problem appear:
Wrapper being used has been invalidated.
code of simulation:

simulation = application.Simulation;
simulation.TimeMode = SimulationTimeMode.VirtualTime;
simulation.SimulationStopped += Simulation_SimulationStopped;
simulation.Reset();
simulation.RunTime = 100;
simulation.SpeedFactor = 4;
simulation.WarmupTime = 0;
simulation.Run(100);

I feel issue is not with the code you are showing, are you accessing other elements of the simulation?

I add a SimulationStopped event,when it happened I will check Collision by CollisionDetected event.if there is a collision in the process of simulation the program will adjust some parameters automatically and generate path again,and restart the simulation. The whole process will be continuing until there is no collision in the simulation process

When I debugging I find it will catch the exception in the row which is the first code to add Statement for robotprogram
The row code:

ICommentStatement linermotion = mainroutine.AddStatement<ICommentStatement>();

if you get the exception at that point the it means that somehow mainroutine was invalidated (robot,or robot program was deleted?). You can subscribe to the ObjectInvalidated event of that object to determine the point when it gets invalidated, or check IsValid property before using it.