Button to stop infinite loops in main thread C# (like Processing)

Hi, I’m making a little template to make processing (http://processing.org) like projects in Rhino, which has a infinite loop that runs a single “draw” function.

I’ve tried to customize the rhinocommon examples, but currently hangs-up when I try to stop the loop. Is there a way to make a window to stop the iteration in the main thread? My current code looks like this.

    private RhinoDoc m_doc;
    
    private Window m_window;
    private StackPanel m_stackpanel;
    private Button m_button;

    private bool stop_iteration; // this stops the infinite loop
    private int frameno;


    protected override Result RunCommand(RhinoDoc doc, RunMode mode)
    {
        m_doc = doc;

        stop_iteration = false;
        frameno = 0;

        m_window = new Window
        {
            Title = "loop stopper",
            Width = 100,
            Height = 50
        };

        m_button = new Button();
        m_button.Content = "stop";
        m_button.Click += Button_click;

        m_stackpanel = new StackPanel();
        m_stackpanel.Children.Add(m_button);

        m_window.Content = m_stackpanel;

        new System.Windows.Interop.WindowInteropHelper(m_window).Owner = Rhino.RhinoApp.MainWindowHandle();
        m_window.Show();

        // this iterates until the button is clicked
        while (!stop_iteration) {
            Draw();
            m_doc.Views.Redraw();
            frameno++;
        }

        return Result.Success;
    }

    private void Button_click(object sender, EventArgs e) {
        stop_iteration = true;
        RhinoApp.WriteLine("stop iteration");
    }

    private void Draw() {

        // do something here
        Thread.Sleep(5000);
        m_doc.Objects.AddSphere(new Sphere(new Point3d(0,frameno*10,0), 3));

    }

I was able to do the same concept in rhinopython using the escape key, https://gist.github.com/yasushisakai/0394ed326ced6f789117#file-rhinoprocessing-py

Is this direction right? Anything will help, and thanks in advance :slight_smile:

In your while loop, call RhinoApp.Wait() to keep the message pump of Rhino alive. This will allow you to click the button which interrupts the loop.