How to execute code on game thread, using AsyncTask or something like that?

So I am working on a plugin which uses mutlithreading, the problem is: I need to debug some stuff on the game thread. This is what I tried:

#include "Async.h"

...	
TArray<FCoverGeneration_CoverStruct>& CoverPoints = Covers;
AActor* ActorToSaveTo = This;
AsyncTask(ENamedThreads::GameThread, [CoverPoints, ActorToSaveTo]()
	{	
		ACoverGeneration_BasicCoverActor* Cover = Cast<ACoverGeneration_BasicCoverActor>(ActorToSaveTo);
		if (Cover != NULL)
		{
			Cover->Covers.Append(CoverPoints);
			Cover->DebugVectors();
		}
		else
		{
			UE_LOG(LogTemp, Warning, TEXT("Cast to BasicCoverActor failed!"));
		}
	});

It compiles, but once the code gets to here the engine crashes.

Does anyone know what I am doing wrong, thanks in advance.

anyone who knows this?

TArray<FCoverGeneration_CoverStruct>& CoverPoints = Covers;

It might be that you are passing through a reference to that array instead of a copy. Try doing the following and see if that fixes your issue;

TArray<FCoverGeneration_CoverStruct> CoverPoints = Covers;

I have just tried that, unfortunatly that doens’t work. Thanks for your reply though.

Also I have tried commenting everything out in the ASyncTask lambda and now it doens’t crash, so it is in the lines:

	AsyncTask(ENamedThreads::GameThread, [CoverPoints, ActorToSaveTo]()
	{	
		ACoverGeneration_BasicCoverActor* Cover = Cast<ACoverGeneration_BasicCoverActor>(ActorToSaveTo);
		if (Cover != NULL)
		{
			Cover->Covers.Append(CoverPoints);
			Cover->DebugVectors();
		}
		else
		{
			UE_LOG(LogTemp, Warning, TEXT("Cast to BasicCoverActor failed!"));
		}
	});

After more research, it sems that the cast causes the crash, but I don’t know why.

You are running into an assert during the cast. You’ll probably break at check(IsInGameThread()); if you attach a debugger.

Multi-Threading: What Not to Do

I have a way to properly execute code on the gamethread:

#include "Async.h"

1.     AsyncTask(ENamedThreads::GameThread, [=]()
2.     {    
PushToActor(This, Covers);
13.     });


void AGeneratCoversThread::PushToActor(AActor* ActorToSaveTo, TArray<FCoverGeneration_CoverStruct> Coverpoints)
{
3.         ACoverGeneration_BasicCoverActor* Cover = Cast<ACoverGeneration_BasicCoverActor>(ActorToSaveTo);
4.         if (Cover != NULL)
5.         {
6.             Cover->Covers.Append(CoverPoints);
7.             Cover->DebugVectors();
8.         }
9.         else
10.         {
11.             UE_LOG(LogTemp, Warning, TEXT("Cast to BasicCoverActor failed!"));
12.         }
}
1 Like