Archived Forum Post

Index of archived forum posts

Question:

How does one cleanup the Task object after the task has completed? (in C++)

Sep 24 '15 at 10:06

How does one cleanup the Task object after the task has completed? (in C++)


Answer

The CkTask object may be deleted immediately after calling the Run method. All Ck* objects are really just wrappers around a reference-counted underlying implementation object (the "Cls" objects -- which are not publicly exposed C++ classes). When a task begins in the background thread, the background thread has a reference to the underlying ClsTask object. Therefore, the app's CkTask object may be deleted. When the TaskCompleted callback happens, the CkTask reference that is passed to it is actually a new CkTask wrapper around the same instance of the "ClsTask" internal object.

Here's a code sample:

static bool _taskCompletedCallbackHappened = false;

class MyTaskProgress : public CkHttpProgress {

public: MyTaskProgress() { printf("constructorn"); }; virtual ~MyTaskProgress() {};

void TaskCompleted(CkTask &task) 
{ 
    // The CkTask object passed in here is actually a new CkTask wrapper
    //wrapped around the same internal ClsTask implementation object..
printf("TaskCompleted called\n"); 
_taskCompletedCallbackHappened = true;
};

};

static MyTaskProgress _taskProgress;

bool AsyncTesting::qa_asyncTaskCompleted(void) { CkHttp http;

// Always make sure to set the EventCallbackObject before 
// calling the Async method..
http.put_EventCallbackObject(&_taskProgress);
CkTask *task = http.GetHeadAsync("http://www.chilkatsoft.com/");

task->Run();
// It is OK to delete the CkTask object here..
delete task;

// Let's hang around to see if the callback happens and the task completes.
// (We don't have to do this..  
// the application could instead continue with anything else)   
while (!_taskCompletedCallbackHappened)
{
Sleep(10);
}

printf("qa_asyncTaskCompleted success");
return true;
}