How to stop the thread?

Hi there!

I need to interrupt a task in arbitrarily time. Cancel() does not work, waiting for the completion.

How call function from it to stop? There is a way to stop the task without ending?

I need to call StopWork(). And don’t use static function.

Whan I do it editor crash with error "Assertion failed: WorkNotFinishedCounter.GetValue() == 0 [File:E:\Program Files\Epic Games\4.13\Engine\Source\Runtime\Core\Public\Async\AsyncWork.h] [Line: 307] "

because:

Retrieve embedded user job, not legal to call while a job is in process

Is there a way? Thanks.


#pragma once

class YimerTh : public FNonAbandonableTask
{
public:

    YimerTh();

    bool bRun = false;

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

    void DoWork();
    void StopWork();

};


#include "ThreadProject.h"
#include "YimerTh.h"

YimerTh::YimerTh()
{
    bRun = true;
}

void YimerTh::DoWork()
{
    while (bRun)
    {
        FPlatformProcess::Sleep(1.f);

        GLog->Log("YimerTh::DoWork()");
    }
}

void YimerTh::StopWork()
{
    bRun = false;
}


FAsyncTask<YimerTh> * NewTimer = new FAsyncTask<YimerTh>();
NewTimer->GetTask().StopWork();

Try modify the declaration of bRun to



volatile bool bRun = false;


And also, you may need to sleep for a few ms before the thread really quits.

No it does not work, still the engine crash when I call variables from outside, when thread working. The same error.

I do like this:


NewTimer->GetTask().bRun = false;

The keyword volatile is necessary because otherwise, C++ compiler will optimize bRun variable (and maybe transform it as register). So when bRun is set to true outside of the thread, the bRun inside thread remains false - I have faced similar problem like yours.

I modify the declaration of bRun to volatile.
bRun does not change outside at all, just crash.