I want to do a simple thing (assuming that ContinueWith is thread-safe):
readonly Task _task = Task.CompletedTask;
// thread A: conditionally prolong the task
if(condition)
_task.ContinueWith(o => ...);
// thread B: await for everything
await _task;
Problem: in above code await _task immediately returns, disregards if there are inner tasks.
Extending requirement that _task can be prolonged by multiple ContinueWith, how would I await for all of them to finish?
Of course I can try to do it in old thread-safe way:
Task _task = Task.CompletedTask;
readonly object _lock = new object();
// thread A
if(condition)
_lock(_lock)
_task = _task.ContinueWith(o => ...); // storing the latest inner task
// thread B
lock(_lock)
await _task;
Or by storing tasks in thread-safe collection and using Task.WaitAll.
But I was curious if there is an easy fix to a first snippet?
In your original code
await _task;returns immediately becausetaskis completed. You need to doYou don't have to use locks. You are working in the same thread. In your "locks" version of the code, you do use
_task = _task.ContinueWith(...)and that is why it works, not because of the locks.EDIT: Just saw that you want to do
_task = _task.ContinueWith(...);in one thread and_task = _task.ContinueWith(...).This is quite bad as design. You should never combine threads and tasks. You should either go for a task-only solution, or for a thread-only solution.
If you go for a task-only solution (recommended), just create a good sequence of work tasks and then on each task decide how to proceed based on the result of the previous task(s).
If you go for a thread-only solution, you might want to use
ManualResetEventhandles to synchronize your tasks.