Firstly, ContinueWith will return a new Task , you want to wait for the Complete method to Complete , but you are waiting for the first task t .
So, to bring Complete to end test , you have to wait for the second task:
Task t = new Task(async () => await Get(), cancel.Token); // NOTE: t2 is a new Task returned from ContinueWith Task t2 = t.ContinueWith(Complete); if (tasks.TryAdd(id, t)) { t.Start(); } else { } // NOTE: Waiting on t2, NOT t t2.Wait(); Console.WriteLine("end test");
Now the output will be:
start task Complete end test end task
Well, this is still not the expected result. end task should be printed before Complete . This is because your asynchronous action is not expected: How to wait for an async delegate
I donβt know if I understood your requirements correctly. If so, I can do it like this:
Add a new supporting class:
public class TaskEntry { public Task Task { get; set; } }
Then change your code to:
Guid id = Guid.NewGuid(); Task task = null; var entry = new TaskEntry(); if (tasks.TryAdd(id, entry)) { entry.Task = Get(); // Notice this line of code: task = entry.Task.ContinueWith(Complete); } if (task != null) { task.Wait(); } Console.WriteLine("end test");
Here I assume that TaskEntry will not be modified by other threads.
source share