C# component event subscription bug

I’ve noticed a very annoying event related bug in c# script component.
After closing and reopening a c# component with event subscriptions all the delegates are subscribed once again. I need to restart Rhino to make all delegates work as expected after each change in my code.

Here is an example:

private void RunScript(bool x, object y, ref object A)
  {
    GrasshopperDocument.SolutionStart -= PrintStart;
    GrasshopperDocument.SolutionStart += PrintStart;

    GrasshopperDocument.SolutionEnd -= PrintEnd;
    GrasshopperDocument.SolutionEnd += PrintEnd;
  }

  // <Custom additional code> 

  public void PrintStart(object sender, GH_SolutionEventArgs e)
  {
    RhinoApp.WriteLine("Before solution!");
  }

  public void PrintEnd(object sender, GH_SolutionEventArgs e)
  {
    RhinoApp.WriteLine("After solution!");
  }

You would expect to have

Before solution!
After solution!

in the Rhino command line after each solution is calculated. And it works exactly like that before you reopen c# script, add another empty line or edit your code somehow. Then boom:

Before solution!
Before solution!
After solution!
After solution!

Edit your code once again and get a triple result. And so on.
The only way to reset things to normal is to restart Rhino.

eventBug.gh (2.9 KB)

That is because when you change the script, all the code is like a new instance. The methods you subscribed with no longer exist when the code is compiled again, you have a new version of them, so you cannot unsubscribe with them.

It’s very annoying, I know. What I do is plug in a toggle button to use this boolean value as a condition to subscribe or subscribe to the method, and before I change the code I set the toggle to false. Another option, which depends on what you want to do, is to put the line to unsubscribe inside the body of the method that is launched with the event.

2 Likes