In this article, we delve into the equivalent helper functions for C# and JavaScript, which are simpler due to the inherent behavior of references in these languages, eliminating the need for explicit shared pointer conversions.
On Writing Loops in Continuation-passing Style, Part 4
By Raymond Chen
From the article:
So far, we’ve been look at writing loops in PPL and continuation-passing style, and a lot of the complications came from creating
shared_ptr
s to manage shared state without copying, and trying to reduce the number of such pointers we had to make. The equivalent helper functions in C# and JavaScript are simpler because in those languages, references act likeshared_ptr
already; there’s no need to convert them into shared pointers explicitly.class TaskHelpers { public static Task DoWhileTask(Func<Task<bool>> callable) { return callable().ContinueWith(t => t.Result ? DoWhileTask(callable) : Task.CompletedTask).Unwrap(); } }The C# Task Parallel Library’s
ContinueWith
method is the equivalent to the PPLthen()
method: You give it aFunc<Task<T>, Result>
which is called with the preceding task. In our case, we are given aTask<bool>
: We check the result, and if it istrue
, then we recurse back and do the whole thing again.The gotcha is that
ContinueWith
returns a task whose result type matches the return value of theFunc
you passed in. In our case, thatFunc
returns aTask
, so the return value ofContinueWith
is a rather confusingTask<Task>
. You need to follow up with theUnwrap()
method to unwrap one layer and get aTask
back. (More generally, theUnwrap
method converts aTask<Task<T>>
to aTask<T>
.)
Add a Comment
Comments are closed.