Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task does not wait for ContinueWith to finish

Tags:

c#

task

I have console application and code as below,

My problem is before ContinueWith task finish, the console application ends, it does not waits the continueWith to finish, please advise.

Please let me know what I am missing or incorrect.

var task1 = Task<bool>.Factory.StartNew(() => DoProcess());

task1 .ContinueWith(
     t1 => updateSuccess(),
       TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.ExecuteSynchronously);

task1 .ContinueWith(
     t => updateFault(),
     TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);

task1.Wait();
like image 356
Keshavdas M Avatar asked Jan 10 '23 12:01

Keshavdas M


1 Answers

You have to wait on the task to complete from the main thread. Simplified it'll look like

var task1 = Task<bool>.Factory.StartNew(() => DoProcess());

successContinuation = task1 .ContinueWith(t1 => updateSuccess(),
                                          TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.ExecuteSynchronously)
failureContinuation = task1 .ContinueWith( t => updateFault(),
                                          TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);

Task.WaitAny(successContinuation, failureContinuation);

I think you're not realizing that you're creating a task that will (actually just may) execute in a different thread. The moment you start your task you have two different threads of execution the main thread, which will continue to run, and your task. If you want your main thread (your console application) to wait for the task to finish, you have to manually specify it.

like image 63
Jorge Córdoba Avatar answered Jan 22 '23 02:01

Jorge Córdoba