In javascript it is possible to prevent a "too much recursion" error, when a method is calling itself, by wrapping the recursive call in setTimeout
. For example, this eventhandler adds one item at a time to a knockout observable array, using array.shift()
and recursion instead of a loop:
$(document).on("AddPizzaFan", function (event, data, results) {
var item = data.shift();
var fan = new PizzaFan(
item['firstname'],
item['lastname'],
item['favoritePizzaTopping']
)
myObservableArray.push(fan);
if (data.length > 0) {
setTimeout(function () { $(document).trigger("AddPizzaFan", [data, myObservableArray]); }, 1);
}
});
This approach allows a UI component bound to the KO observable to be updated one data row at a time, making the UI seem fast and responsive even when data
contains thousands of rows and might otherwise require 5 or 10 or even 60 seconds or more to appear if the data
array was simply fed all at once to the UI. When the array is fed to the UI in many small bits, the user starts to see data on the screen right away. (FWIW, the actual application is a text corpora search where many paragraphs of text are returned which contain the user's search term or search phrase.)
Can something comparable to this be done with a Stack
and async await
in C# ? Reading this question and answer, it seems that it can't, at least not easily. If it is possible to do something similar in C#, how is it accomplished?