Best practices to run asynchronous code inside SolveInstance

Hey, so I’m making a component that runs an async method inside of SolveInstance in order to get the output of the component. Besides the output, the inputs of the component can also modified because of the result from this async method.

So… this works fine if I use simple primitive parameters such as number inputs, etc. However, I start having unexpected stuff happening (e.g. multiple outputs, wrong outputs) when I use more “dynamic” input components such as number sliders, etc. I imagine this is happening because of out-of-date results from the async method which are not returned in time…

What are some good approaches to use async methods inside of SolveInstance?

Thank you :slight_smile:

Can you post any example? Hard to tell without…

You could store in the async method also a timestamp of the input, when the method finish, check the last input timestamp is unchanged and only then output the result.

Or kill any active async methods if a new input triggers.

Hey! Yeah sure, below is some pseudo-code that shows the logic that I’m trying to implement:

private myDS = new DS();

protected override async void SolveInternal(IGH_DataAccess DA)
{
  // Update the values of DS
  await DS.updateDS(); // This sends a request and updates DS with part of the results
  
  if (condition(DS))
  {
    // update component ui (only) if a condition is met
    OnPingDocument().ScheduleSolution(1, updateInputs);
  }
  else
  {
  // Get the results and set them as the output (doesnt update the component ui). Can potentially take a longer time to get the results back from the server.
  dynamic results = await DS.getResuts(); // This sends a request and updates DS with some results (results can have multiple types depending on getResults)
  DA.SetData(0, results);
  }
}

Currently I’m forcing the async methods to run synchronously, which isn’t ideal… My component is using IGH_VariableParameterComponent since it requires dynamic inputs/outputs.

Best practice is not using async at all. All you achieve is that UI does not block while you are waiting for your long operation to complete. The question is just, what does it help you if you can use the UI, while you wait for your long operation to complete. I cannot imagine that its truly thread-safe if you modify a definition while its waiting for some data to fetch. Have you tried to delete it, while its fetching data? Don’t get me wrong, I’m a big fan of concurrent programming. I just don’t see the benefit in GH1.

ehi Tomas.
How do you force your method to run synchronously?

I am also facing the same issue