How to execute asynchronous code from a custom code activity?

I created a custom CodeActivity in C# that I am using in a sequence within a state machine in UiPath. The custom CodeActivity involves calling an API through an async method.

I cannot get it to work.

I’ve tried using AsyncCodeActivity using this method: https://stackoverflow.com/a/16964323/989148

I’ve also tried:

  • task.GetAwaiter().GetResult();
  • task.Result;
  • task.ConfigureAwait(false).GetAwaiter().GetResult()

Nothing works.

In some cases the robot just never ends. In other cases the robot fails with an error message: “An Activity can only get the location of arguments which it owns.”. This happens when I try to access the output value of the activity.

How can I do an async method call within a CodeActivity in UiPath?

2 Likes

Good evening Bena,

Classes that derive from CodeActivity are synchronous by default. Since UiPath is based on Windows Workflow, deriving from an AsyncCodeActivity class should work.

You’ll need to inherit from AsyncCodeActivity<T> (<T> being optional) and implement both BeginExecute and EndExecute. But besides that, they don’t differ much, as the framework takes good care of managing the async part.

3 Likes

As we have the Inherited class of Execute within the code activity, you need to use a await modifier while assigning the result of the function return @Bena

I hope you are missing this particular thing

1 Like

Here is an example of a simple test AsyncCodeActivity that waits for 1 minute and then sets an output variable.

This example uses the ApmAsyncFactory from the Nito.AsyncEx.Interop library.

I put it in my flow in UiPath and direct the output string to a variable. After the execution of the custom activity I try to popup a message box with the value of the variable.

When executing this the robot waits for 1 minute (the delay I put in my custom activity) and then I get an error.

3 Likes

I am following your sample to build one of my async code but I cannot find out how to get/use AsyncTaskCodeActivity. Could you explain where it could be found in VisualStudio?