I am refactoring "synchronous" code (that is, using Windows events to wait for some other thread to finish doing something) with "asynchronous" code (using delegates to implement the callback mechanism).
In the synchronization code, I sometimes have local variables that I need to use after the wait is over. When such code runs asynchronously, these local variables are lost (the callback handler cannot access them). I can store them as attributes of a class, but it looks wasteful.
In C ++, I use std::bind to get around this. I simply add as many parameters as the local variables needed for the callback handler and bind them when I call the async method. For example, say that an asynchronous method callback receives an object of type CallbackParam , and the caller uses two local variables of type LocalA and LocalB .
void AsyncClass::MethodWhichCallsAsyncMethod(){ LocalA localVarA; LocalB localVarB; // OnAsyncMethodDone will need localVarA and localVarB, so we 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 to be done }
Is there any equivalent to this in C # and VB.NET? Using delegates or something else?
UPDATE . For completeness, here is the C # equivalent of my example, based on @lasseespeholt answer:
using System; public class AsyncClass { public void MethodWhichCallsAsyncMethod() { var a = new LocalA(); var b = new LocalB();
source share