Pavel Voronin
Pavel Voronin

Reputation: 14005

What is the robust way to create continuation for already exceuting task?

Let us have running task mainTask. Then something happens and I want to schedule the continuation.

mainTask.ContinueWith(continuationTask);

But this won't work if mainTask is completed at that moment. <- WRONG STATEMENT
Ok, we could perfrom some check:

if (mainTask.IsCompleted)
{
    continuationTask.Start();
}
else 
{
    mainTask.ContinueWith(continuationTask);
}

And this is not safe either because we can have task not completed when checking and completed just before creating the continuation.
Hence comes the question how can task be continued dynamically?

The only solution I see now is creating the third task:

var waitingTask = new Task ( () => mainTask.Wait());
waitingTask.ContinueWith(continuationTask);
waitingTask.Start();

But I'd like to know whether more elegant way exists.

Upvotes: 2

Views: 64

Answers (1)

usr
usr

Reputation: 171236

But this won't work if mainTask is completed at that moment.

That's not true.

You need to create a self-contained repro to find help. By doing that you'll find out that your assumption is false and that there is a bug somewhere.

Upvotes: 4

Related Questions