Say I have a Task
that generates an int
, and a callback that accepts an int
:
Task<int> task = ...;
Action<int> f = ...;
Now I want to set it up so that once the task has completed and returned its integer result, the callfack f
will be called with that integer – without requiring the main thread to wait for the task to complete:
As I understand it, the typical solution for this is the
Task.ContinueWith
method:task.ContinueWith(t => f(t.Result));
However, one could also get a
TaskAwaiter
for the task, and use its event-like interface:TaskAwaiter<int> awaiter = task.GetAwaiter(); awaiter.OnCompleted(() => f(awaiter.GetResult()));
Now, I realize that TaskAwaiter
is not intended for common use in application code, and mainly exists to be used internally by the await
keyword.
But in order to deepen my understanding of the TPL, I'm wondering:
Is there any practical difference between solutions (1) and (2)?
For example,
- ...regarding on which thread the callback will be invoked?
- ...regarding what happens when an exception is thrown in the task or callback?
- ...any other side-effects?