How to create a task in game thread and wait for it?

In a plugin whose code is not on game thread, I want to use some functions from EditorAssetLibrary, which must be executed in game thread to work.

I tried the following code piece, but the whole engine GUI freezes. Seems that it is waiting for the task to complete foreverly.

FGraphEventRef Task = FFunctionGraphTask::CreateAndDispatchWhenReady([]()
{
    // Do something in game thread
    // Modify variable "Result"
}, TStatId(), nullptr, ENamedThreads::GameThread);

// Wait for the task
FTaskGraphInterface::Get().WaitUntilTaskCompletes(Task);

return Result;

Why do you want to wait on the task?

Could you instead give the task a delegate to call when complete to move your logic forward?

Make a static function in you .h file

static FGraphEventRef RunLambdaOnGameThread(TFunction< void()> InFunction);

In CPP

FGraphEventRef YouClassName::RunLambdaOnGameThread(TFunction< void()> InFunction)
  {
return FFunctionGraphTask::CreateAndDispatchWhenReady(InFunction, TStatId(), nullptr, ENamedThreads::GameThread);
  }

Now you can run a function on the game thread.

void YourClassName::YourFunc(params)
{
	RunLambdaOnGameThread([capture any vars by ref or by value] {
              // Your func Implementation
       });
}

Hope this helps.

2 Likes