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_ptrs 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_ptralready; 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
ContinueWithmethod 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
ContinueWithreturns a task whose result type matches the return value of theFuncyou passed in. In our case, thatFuncreturns aTask, so the return value ofContinueWithis a rather confusingTask<Task>. You need to follow up with theUnwrap()method to unwrap one layer and get aTaskback. (More generally, theUnwrapmethod converts aTask<Task<T>>to aTask<T>.)

Add a Comment
Comments are closed.