c++ - std::bind equivalent in C# or VB.NET -
i in process of refactoring "synchronous" code (i.e. uses windows events wait until other thread finished doing something) "asynchronous" code (using delegates implement callback mechanism).
in sync code, have local variables need use after wait over. when code goes async, local variables lost (the callback handler can't access them). can store them class attributes, feels wasteful.
in c++, use std::bind
work around this. add many parameters local variables needed callback handler, , bind them when call async method. example, let's async method callback receives object of type callbackparam
, caller uses 2 local variables of type locala
, localb
.
void asyncclass::methodwhichcallsasyncmethod(){ locala localvara; localb localvarb; // onasyncmethoddone need localvara , localvarb, bind them asyncmethod( std::bind( &asyncclass::onasyncmethoddone, this, std::placeholders::_1, localvara, localvarb ) ); } void asynclass::asyncmethod( std::function<void(callbackparam)> callback ){ callbackparam result; //compute result... if( callback ) callback( result ); } void asyncclass::onasyncmethoddone( callbackparam p, locala a, localb b ){ //do whatever needs done }
is there sort of equivalent in c# , vb.net? using delegates or else?
update: completeness' sake, here c# equivalent of example based on @lasseespeholt's answer:
using system; public class asyncclass { public void methodwhichcallsasyncmethod() { var = new locala(); var b = new localb(); //anonymous callback handler (equivalent asyncclass::onasyncmethoddone) action<callbackparam> callback = result => { //do needs done; result, , b can accessed }; asyncmethod( callback ); } private void asyncmethod( action<callbackparam> callback ) { var result = new callbackparam(); //compute result... if( callback != null ) callback( result ); } }
update: should not used. use async/await keywords in c#
you can exploit closures following:
void methodwhichcallsasyncmethod() { int foo = 1; asynccallback callback = result => { console.writeline(foo); // access foo }; asyncmethod(callback); } void asyncmethod(asynccallback callback) { iasyncresult result = null; // compute result callback(result); }
the compiler generates class contains "foo" don't save approach, it's clean.
Comments
Post a Comment