How to do some thing,when the component itself been deleted?

i am writing a custom component ,i create a thread to do something.
main code is like this:

my question is : if i delete this component from canvas (when the thread is running),how to do to stop the thread and delete the thread ?
thank you!

  1. Please don’t use Thread.Sleep, it locks up that thread for a second. You can use a System.Threading.Timer to get a callback a second from now.
  2. Don’t call ActiveCanvas.Document without checking for null, there may not be a document loaded.
  3. To solve your issue, your NewThreadMethod needs to be able to tell when it is supposed to stop. As a general rule, you don’t kill threads, you ask them to commit suicide.

There are several ways of achieving (2), you could for example embed the NewThreadMethod in a class of its own, which has some fields that give it the necessary context.

class ThreadContext
  private readonly GH_Component _owner;
  public ThreadContext(GH_Component owner)
    _owner = owner;

  public void Method()
      Thread.Sleep(1000); // yeah, nah.
      GH_Document doc = _owner.OnPingDocument();
      if (doc == null) break;
      doc.ScheduleSolution(1, UpdateSetData);

  private void UpdateSetData(GH_Document doc)

thank you david, why need to check the doc?the gh doc should be always exist…

The user can easily close all documents, in which case there won’t be anything left in the active canvas. Actually there are moments during the Grasshopper lifetime when even the ActiveCanvas isn’t loaded.

1 Like