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

**URL:** <https://forums.unrealengine.com/t/how-to-create-a-task-in-game-thread-and-wait-for-it/490735>\
**Category:** Plugins\
**Tags:** threads, freeze, unreal-engine, Plugins, question\
**Created:** [November 19, 2021, 6:56am UTC](https://forums.unrealengine.com/t/how-to-create-a-task-in-game-thread-and-wait-for-it/490735 "2021-11-19T06:56:11Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jywhy6](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@jywhy6](https://forums.unrealengine.com/u/jywhy6)\
**Post date:** [November 19, 2021, 6:56am UTC](https://forums.unrealengine.com/t/how-to-create-a-task-in-game-thread-and-wait-for-it/490735/1 "2021-11-19T06:56:11Z")

</div>

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;

```

---

<div class="post-metadata">

**Author:** ![Brannigan](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@Brannigan](https://forums.unrealengine.com/u/Brannigan)\
**Post date:** [November 19, 2021, 6:37pm UTC](https://forums.unrealengine.com/t/how-to-create-a-task-in-game-thread-and-wait-for-it/490735/2 "2021-11-19T18:37:01Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![umar5291219](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@umar5291219](https://forums.unrealengine.com/u/umar5291219)\
**Post date:** [October 22, 2022, 8:41am UTC](https://forums.unrealengine.com/t/how-to-create-a-task-in-game-thread-and-wait-for-it/490735/3 "2022-10-22T08:41:30Z")

</div>

Make a static function in you .h file

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

```

In CPP

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

```

Now you can run a function on the game thread.

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

```

Hope this helps.
