FAsyncTask
和 FAutoDeleteAsyncTask
,一般声明为友元函数,FNonAbandonableTask 派生类作为模板FNonAbandonableTask
是要继承的基类,不可被终止的任务,可以看作是任务执行体的抽象DoWork()
实现具体任务,自定义类作为模板参数StartBackgroundTask()
将任务扔到线程池中去执行StartSynchronousTask()
直接在当前线程执行EnsureCompletion()
可以等待任务完成SimpleAsyncTask 类
class SimpleAsyncTask :FNonAbandonableTask { FString m_TaskName; int32 m_MaxNumber; friend class FAsyncTask<SimpleAsyncTask>; public: // 构造函数 SimpleAsyncTask(const FString& TaskName, int32 MaxNumber) : m_TaskName(TaskName), m_MaxNumber(MaxNumber) {} // 析构函数 ~SimpleAsyncTask() { UE_LOG(LogTemp, Warning, TEXT("Task[%s] End"), *m_TaskName); } // 具体任务逻辑执行 void DoWork() { UE_LOG(LogTemp, Warning, TEXT("Task[%s] Start"), *m_TaskName); int CurrentNum = 0; while (CurrentNum < m_MaxNumber) { CurrentNum++; UE_LOG(LogTemp, Warning, TEXT("Task[%s] CurrentNum:%d"), *m_TaskName, CurrentNum); } } // 固定写法,本类将作为函数参数 FORCEINLINE TStatId GetStatId() const { RETURN_QUICK_DECLARE_CYCLE_STAT(SimpleAsyncTask, STATGROUP_ThreadPoolAsyncTasks); } };
调用任务的Actor——AAsyncTaskActor
UFUNCTION(BlueprintCallable) void CreateAsyncTask(const FString& TaskName, int32 MaxNumber);
void AAsyncTaskActor::CreateAsyncTask(const FString& TaskName, int32 MaxNumber) { UE_LOG(LogTemp, Warning, TEXT("Task[%s] Created"), *TaskName); FAsyncTask<SimpleAsyncTask>* MyTask = new FAsyncTask<SimpleAsyncTask>(TaskName, MaxNumber); MyTask->StartBackgroundTask(); // MyTask->StartSynchronousTask; 在当前线程执行,可能会导致主线程阻塞 // MyTask->IsDone() 可以配合定时器检测是否完成任务 //等待任务完成后,进行手动删除 MyTask->EnsureCompletion(); delete MyTask; MyTask = nullptr; }
AutoDeleteSimpleAsyncTask 类
class AutoDeleteSimpleAsyncTask :FNonAbandonableTask { FString m_TaskName; int32 m_MaxNumber; friend class FAutoDeleteAsyncTask<AutoDeleteSimpleAsyncTask>; public: // 构造函数 AutoDeleteSimpleAsyncTask(const FString& TaskName, int32 MaxNumber) : m_TaskName(TaskName), m_MaxNumber(MaxNumber) {} // 析构函数 ~AutoDeleteSimpleAsyncTask() { UE_LOG(LogTemp, Warning, TEXT("Task[%s] End"), *m_TaskName); } // 具体任务逻辑执行 void DoWork() { UE_LOG(LogTemp, Warning, TEXT("Task[%s] Start"), *m_TaskName); int CurrentNum = 0; while (CurrentNum < m_MaxNumber) { CurrentNum++; UE_LOG(LogTemp, Warning, TEXT("AutoDeleteTask[%s] CurrentNum:%d"), *m_TaskName, CurrentNum); } } // 固定写法,本类将作为函数参数 FORCEINLINE TStatId GetStatId() const { RETURN_QUICK_DECLARE_CYCLE_STAT(SimpleAsyncTask, STATGROUP_ThreadPoolAsyncTasks); } };
调用任务的Actor——AAsyncTaskActor
UFUNCTION(BlueprintCallable) void CreateAutoDeleteAsyncTask(const FString& TaskName, int32 MaxNumber);
void AAsyncTaskActor::CreateAutoDeleteAsyncTask(const FString& TaskName, int32 MaxNumber) { UE_LOG(LogTemp, Warning, TEXT("AutoDeleteTask[%s] Created"), *TaskName); // 任务完成后,自动删除 (new FAutoDeleteAsyncTask<AutoDeleteSimpleAsyncTask>(TaskName, MaxNumber))->StartSynchronousTask(); }