System.InvalidOperationException: Cross-thread operation not valid

I created a counter component. It asynchronously expires itself every half a second:

private void expireSolutionAfterDelay(IGH_DataAccess DA)
{
    Task.Delay(500).ContinueWith((task) => {
        ExpireSolution(true);
    });
}

protected override void SolveInstance(IGH_DataAccess DA)
{
    DA.SetData(0, counter);
    expireSolutionAfterDelay(DA);
    counter++;
}

Project.zip (879.4 KB)

When I insert this component I get:

What am I doing wrong?

I hope this example is not over simplified and helps me solve the actual more complex problem: Data is received asynchronously from a server. The component should expire itself every time a new data package is received.

I think you need to invoke ExpireSolution(true) on the UI thread.

I’m lost: How do I do that?

At the moment, I call ExpireSolution(true) on the component, which according to documentation I think should be the right thing to do.

If you like, you can open my project. It’s stripped down to the bare minimum to replicate the issue.

See here:

Thanks, it works with RhinoApp.InvokeOnUiThread()!

I changed:

Task.Delay(500).ContinueWith((task) => {
    ExpireSolution(true);
});

To:

var d = new ExpireSolutionDelegate(ExpireSolution);
Task.Delay(500).ContinueWith((task) => {
    Rhino.RhinoApp.InvokeOnUiThread(d, true);
});

With:

public delegate void ExpireSolutionDelegate(Boolean recompute);
1 Like