Non-static AsyncTask

Hi,

I’m in the early stages of writing a server and I’d like to use an object instance for each player. They all have their own physics state that rely on async tasks, amongst other things. As far as I can tell AsyncTasks have to be static (at least that’s the only way I can get them to work). That will be a problem as I’d like each task to be instance dependent. So I wondered if there was a trick to running tasks in an OO way. The function pointer when creating the task always trips me up if I don’t make it static, so maybe I’m lacking some C++ knowledge there.

Thanks,

The task handlers must be static, however it can take a void* parameter which I used to pass the actual instance of a class.

class.h

class MyClass
{        
    private:
        void add_the_task();
        AsyncTask::DoneStatus my_task(GenericAsyncTask* task);
        static AsyncTask::DoneStatus my_task_static(GenericAsyncTask* task, void* data);
};

class.cxx

AsyncTask::DoneStatus MyClass::my_task(GenericAsyncTask* task)
{
   // do something
   return AsyncTask::Done;
}

AsyncTask::DoneStatus MyClass::my_task_static(GenericAsyncTask* task, void* data)
{
    return ((MyClass*)data)->my_task(task);
}

void MyClass::add_the_task()
{
    PT(GenericAsyncTask) task = new GenericAsyncTask("mytask", &MyClass::my_task_static, (void*)this);
    task->set_delay(1);
    AsyncTaskManager::get_global_ptr()->add(task);
}

Hi loblão,

Yeah I do that myself with the void pointer. I thought the problem was that the tasks are inside my class. But thinking about it, that should work anyway, regardless of the task function being static because of the instance in the void parameter. So there isn’t actually a problem there. :blush:

Cheers,

An alternative is to override AsyncTask instead and implement the “virtual DoneStatus do_task();” method. You can store whatever parameters you want on your custom AsyncTask object.

Hi rdb,

Yeah that sounds like a good idea, I’ll probably do it that way.

Cheers,
Zobbo