How do you make an async task that returns a TArray?

Hi,

I am fairly new to c++ programming, and I have a function that generates triangles to be used with a procedural mesh component, but I want it to be run as an async task. I am aware that you cannot edit values, or create new mesh sections in an async task, so I just want to call the async task, return the tris, and generate the mesh on the main thread.

How would I implement returning values from an async task that is executed from “begin play”?

Thanks,
Will

Edit: I’ve googled a lot and read the documentation, something about using a delegate as an async task parameter? I am very confused please help!

Should be something like this.



            TFuture<TArray<MyTriangles>> TriangleFuture;
            TriangleFuture = Async(EAsyncExecution::TaskGraph, MyDelegate);

            // Later...
            if(TriangleFuture.IsReady())
            {
                // Process your triangles.
            }
            else
            {
                // Try again next frame or wait.
            }


So I’m assuming MyDelegate is the delegate that calculates the triangles, but what does TFuture do?

Yes, or you can use a lambda.

A TFuture is a thin wrapper that let’s you see if the Async task is done yet or not and what the returned value (in this case, a TArray) is.


    chunkDelegate chunkDel;
    chunkDel.BindUFunction(this, FName("InitChunk"));

    TFuture<TArray<FXYZ>> TriangleFuture;
    TriangleFuture = Async(EAsyncExecution::TaskGraph, chunkDel);

This gives me an error on the Async(EAsyncExecution::TaskGraph, chunkDel) part, I don’t know why.
no instance of function template “Async” matches the argument list

You can look at Async.h for examples, looks like you need to wrap functions in TUniqueFunction:



 *    // using global function
 *        int TestFunc()
 *        {
 *            return 123;
 *        }
 *
 *        TUniqueFunction<int()> Task = TestFunc();
 *        auto Result = Async(EAsyncExecution::Thread, Task);
 *
 *    // using lambda
 *        TUniqueFunction<int()> Task = ]()
 *        {
 *            return 123;
 *        }
 *
 *        auto Result = Async(EAsyncExecution::Thread, Task);
 *
 *
 *    // using inline lambda
 *        auto Result = Async(EAsyncExecution::Thread, ]() {
 *            return 123;
 *        }


Still getting an error on build

TUniqueFunction<TArray<FXYZ,FDefaultAllocator> (void)>::TUniqueFunction(const TUniqueFunction<TArray<FXYZ,FDefaultAllocator> (void)> &)’: attempting to reference a deleted function

Code:


TUniqueFunction<TArray<FXYZ>()> Task = [this, x, y, z, scalarField]()
    {
        TArray<FXYZ> triArray = InitChunk(x, y, z, 0.5, scalarField, scale);
        return triArray;
    };

    Result = Async(EAsyncExecution::Thread, Task);


also, Result is defined in the header file