Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a Task get to know when it has completed?

The Task does not maintain a wait handle for performance reasons, and only lazily constructs one if the code were to ask one of it.

How then does a Task know it has been completed?

One would argue that the implementer sets the result on the TaskCompletionSource in their implementation but that would explain only the modern implementations and re-writes such as System.IO.FileStream.Begin/EndReadTask.

I followed the Task.IsComplete property; almost in every instance, an internal bitwise flag field (m_stateFlags) is set by the TrySetResult / TrySetException methods to indicate the status of the task.

But that does not cover all cases.

What about a method such as this?

public async Task FooAsync()
{
    await Task.Run(() => { });
}
like image 980
Water Cooler v2 Avatar asked Feb 24 '26 20:02

Water Cooler v2


1 Answers

How then does a Task know it has been completed?

As I describe on my blog (overview, more detail), there are two kinds of tasks: Delegate Tasks (which execute code) and Promise Tasks (which represent an event).

Delegate Tasks complete themselves when their delegate completes.

Promise Tasks are completed from an external signal, using TaskCompletionSource<T> (or equivalent methods that are internal to the BCL).

like image 58
Stephen Cleary Avatar answered Feb 26 '26 10:02

Stephen Cleary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!