c# - Asynchronous function call inside tree loader extension function -
c# - Asynchronous function call inside tree loader extension function -
i have function load children of node. internally calls wcf async service load. signature follows.
public void addchildelements(node parentelement, action<ienumerable<node>> callback) { }
this can used like
_nodebuilder.addchildelements(parentelement, (elements) => { //do elements });
now want write function expand hierarchy based on condition. write extension function this
public static t loadhierarchyuntilitemfound<t>( ienumerable<t> sequence, func<t, list<t>> loadaction, func<t, string> searchstring) { //... }
the loadaction parameter expects loading function node.the usage follows
elements.loadhierarchyuntilitemfound(loadchildren, "root.uk.england.london");
the problem how write loading function?
private list<node> loadchildren(node parent) { // _nodebuilder.addchildelements(parent, here expects callback //which gives result, how utilize this?); }
in short, problem how can utilize callback function homecoming result wrapper function?
if want is possible create function calls async method , blocks until returns:
private list<node> loadchildren(node parent) { var tcs = new taskcompletionsource<ienumerable<node>>(); addchildelements(parent, nodes => tcs.setresult(nodes)); homecoming tcs.task.result.tolist(); }
however, in many contexts preferable entire thing asynchronously, rather synchronously.
public static async task<t> loadhierarchyuntilitemfoundasync<t>( ienumerable<t> sequence, func<t, task<ienumerable<t>>> loadaction, func<t, string> selector, string searchstring) { var stack = new stack<t>(sequence); while (stack.any()) { var item = stack.pop(); if (selector(item) == searchstring) homecoming item; foreach (var kid in await loadaction(item)) { stack.push(child); } } homecoming default(t); }
given function can phone call using:
elements.loadhierarchyuntilitemfound(addchildelements, "root.uk.england.london");
c# asynchronous callback hierarchical-data
Comments
Post a Comment