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?