Deferred execution in VB.NET? -


private sub loaddata(of t)(byval query objectquery(of t),      byref result ienumerable(of t))   if connection.state = connectionstate.open     result = query.toarray   else     addhandler connection.statechange,       sub(sender object, e statechangeeventargs)         loaddata(query, result)       end sub   end if end sub 

in above code trying recurse loaddata function when connection unavailable, want defer loading when becomes available.

the problem above code leads compiler error, since a byref param cannot used in lambda expressions.

any idea of how right way?

you cannot use byref parameter in lambda because pointing location on stack no longer exists once lambda execuetes. have use more "permanent" storage location. can pass in object property of ienumerable(of t) can set in order assign result.

a better option pass in delegate (action<ienumerable<t>>) accepts result , performs whatever action caller requires result. here's example in c#:

void loaddata<t>(objectquery<t> query, action<ienumerable<t>> action) {     if (connection.state == connectionstate.open)         action(query.toarray());     else     {         // create lambda handle next state change         statechangeeventhandler lambda = null;         lambda = (sender, e) =>         {             // perform our action on transition open state             if (connection.state == connectionstate.open)             {                 // unsubscribe when we're done                 connection.statechange -= lambda;                 action(query.toarray());             }         }         // subscribe connection state changes         connection.statechange += lambda;     } } 

and invoke loaddata this:

loaddata(query, results => listbox.datasource = results); 

note nuances of implementation. example, not call within event handler because cause resubscribe event if handler ever called state other open. unsubscribes event once connection opens. i'm not sure how translate vb, in c# 3-step process. first must declare variable hold lambda , set value null. create lambda, can reference unsubscribe. , can use lambda subscribe event.


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -