cpprestsdk icon indicating copy to clipboard operation
cpprestsdk copied to clipboard

pplx task lifetime

Open slepasteur opened this issue 10 years ago • 4 comments

Hi,

Is it ok to create a pplx task, giving it some work and never calling wait() or get() on it?

I have some work to do, and need to call a callback once it's done. Therefore, I do not need the result of the task.

void f()
{
    pplx::create_task([]{
        //... do work....
        return result;
    }).then([](auto result){
        // ... handle result ...
    });
}

Will a task created this way be executed correctly even if the result of create task is not used? What happens at the end of the process, will the created tasks block until they are executed?

slepasteur avatar May 31 '16 14:05 slepasteur

Yes, they will execute.

However, at the end of the process, outstanding tasks will not be waited upon -- they will simply be killed. Additionally, if any task in your chain throws an uncaught exception, your process will be terminated (similar to if a thread throws an exception).

To block for outstanding tasks, you need to keep track of them and call .wait() at the end of your main function (a vector<task<void>> works fine for this). This .wait() call is also how exceptions are propagated, so you will probably want to wrap them in try {} catch (...) {} blocks to handle any errors.

ras0219-msft avatar May 31 '16 22:05 ras0219-msft

Thank you for your answer.

It's ok for me if the tasks are killed at the end of the process. In fact my goal is to run tasks from an object and have the last continuation of each task run a callback on this object. Therefore, I intend to cancel all the spawned tasks (with a cancellation token) when this object is destroyed. The exceptions should be handled by the callback continuation.

Is this possible to use tasks this way or should I do it differently?

slepasteur avatar Jun 01 '16 09:06 slepasteur

I would recommend choosing a slightly different approach than you've described. Cancellation tokens only operate "between" tasks, since they cannot interrupt your callback while it's executing. Therefore you cannot effectively use cancellation as a means of synchronization like you're describing -- the callback might already have started and if you destroy the object while it's being accessed in the callback, that's a data race (aka undefined behavior).

To get the behavior you're describing, you'll need to use shared_ptr's for the object and have the final callback task capture a shared_ptr by value. When you want to "destroy" the object, drop all external shared_ptrs and trigger the task cancellation token. This will keep the object alive if the callback is already in progress and destroy the object once the task chain is guaranteed to no longer need access to the object. If the object has a reference to the task, this might result in a ref-count loop; so you may want to have the callback capture a weak_ptr instead.

Alternatively, you can cancel the task chain, then block (or equivalent) on the final callback task to confirm it has completed or cancelled successfully before destroying the object.

ras0219-msft avatar Jun 14 '16 07:06 ras0219-msft

Hi

When I read the answer above => It seems to be ok, to do this: Create a stack pplx::task and leave the scope of the function immediately.

Intension: The calling thread should not be blocked by .wait or .get calls on the created task object.

To keep exceptions from interfering the program, I added the following handlers.

void FireAndForget(AddMessageReqDto newMessageDto) const
{
    pplx::task<void> requestTask = Concurrency::create_task ([=]()
    {
        http_client client(requestUrl);
        return client.request(methods::POST, L"", aJsonString, L"application/json");
    })
    .then([=](pplx::task<web::http::http_response> task)
    {
        try {
            web::http::http_response  response = task.get(); 
	     if (response.status_code() != status_codes::OK)
			// TODO: LOG it!!
        }
        catch(const std::exception& ex)
       {
   		// TODO: LOG it!!
        }
});}

Is this ok??

Thanks and best regards Dieter

duhtmep avatar Nov 08 '17 12:11 duhtmep