During AsyncTask If I exit play mode the Engine Crashes


I have an AsyncTask that sets up connection to database so that there is no delay in the main game thread.

Problem is if lets say it downloads an image and before it has completed I press escape and exit out of play mode the engine crashes.

here is my code:

class MultithreadedTask : public FNonAbandonableTask {public:UObject* object;

// ConstructorMultithreadedTask(UObject* object) { this->object = object; }

FORCEINLINE TStatId GetStatId() const {RETURN_QUICK_DECLARE_CYCLE_STAT(MultithreadedTask, STATGROUP_ThreadPoolAsyncTasks);}

void DoWork(){IIMultithreading::Execute_MultithreadedFunction(object);}};

The Task class is just calling the Execute Interface method with UObject passed as a reference.

and below is the implementation of a blueprint callable function that takes in a UObject and creates and starts a new background task.

void UMultithreadedFunctionLibrary::CallMultithreadedFunction(UObject* Object){(new FAutoDeleteAsyncTask<MultithreadedTask>(Object))->StartBackgroundTask();}

Now, If the task is finished and i exit or change level everything works fine the engine does not crash. but if I change the level or jump out of playmode before the task has finished the engine crashes with Access Violation error messages.

I have tried to use ASyncTasks and manually Cancel and abandon it on BeginDestroy() but it turned out to be even worse than this.

I just don’t want my engine to crash if i switch level or exit play mode

You pass a raw UObject* pointer to the task, so the garbage collector has no idea about it. When you quit the game or change the level, the UObject is destroyed but task think he’s still alive and trying to use it.

If my assumptions are correct, using TWeakObjectPtr and validating before use should help.

1 Like

Alright so, I have managed to send in a TWeakObjectPtr and it works really well thing is now the plugin i am using to connect to MySQL has a Macro that Tries to connect to database is where it crashes if i exit play mode.

I suppose it is also creating a UObject* somewhere and when i exit play mode and the ConnectionOnSuccess or OnFail fires it all comes crashing down.

I think that can be fixed like if on End Play I can somehow just kill all the threads even if they are in mid execution.

The SQL plugin I am using : GitHub - darkgoogle/MysqlDBUnrealengine4.26