Internalize Timer in C# - Simple Counter

You wanted to use a timer inside the component :man_shrugging:, the way to implement it is to subscribe to its Tick event and for that you need a delegate of the type HandlerMethod(object, EventArgs). Every time the timer makes a tick, the UpdateSolution() method is executed. Where to put the user code is in Update().

I thought you wanted it in a compiled component, not in a scripting component, my fault. When you pass it to a scripting component you haven’t passed it correctly, but well, it’s already solved.

Anyway, it’s not a good idea to expire the component directly, without leaving a delay or something, because in case the document takes a long time to compute/respond, it’s hard to stop it. In case of not using a timer (which is not necessary for this) it is more convenient to schedule a new solution with GH_Document.ScheduleSolution().

 private void RunScript(bool reset, bool run, ref object A)
 {

    if(reset)
      counter = 0;

    if(run)
      GrasshopperDocument.ScheduleSolution(100, d => { 
        //Press ctrl to stop it before it breaks.
        if ((Control.ModifierKeys & Keys.Control) == Keys.Control) return;
        this.Component.ExpireSolution(false);
        counter++;
      });

  A = counter;

}

// <Custom additional code>  

public int counter = 0; 

// </Custom additional code>
3 Likes