0

A short purely technical question:

If I have an uncertain amount of overlapping (time-wise) instances of the class below. Is it and how is it ensured, that the "this" in "call_back_when_done" belongs to the same "this" as it was in "Start"?

class MyClass{
 int ident = -1;
 bool ready = false;

 void Start(string url){
  ident = aStaticClass.DoSomethingAndForkThread(url, callback_when_done);
 }

 void call_back_when_done(){
  ready = true;
 }
}

e.g.:

for (int i=0; i < 3; i++)
    new MyClass().Start(<aURL>);

Thank You

Cyril Damm
  • 283
  • 5
  • 7

2 Answers2

0

At first, you can bind the function to "this" like described here using currying : (How) is it possible to bind/rebind a method to work with a delegate of a different signature?

I would prefer a lambda function for your example case like described here : C# Lambdas and "this" variable scope

Lambda functions are bound to the scope of the "this" context where they are created. Members of your surrounding Class are automatically visible to the Lambda function. Using a Lambda function you'll get shorter code which can also better optimized by the compiler.

Community
  • 1
  • 1
lgersman
  • 2,178
  • 2
  • 19
  • 21
0

It is guaranteed. When you pass callback_when_done to DoSomethingAndForkThread in Start, you are not only passing the raw function pointer (like you would in C++ with &MyClass::callback_when_done, but some kind of tuple consisting of the method to call and the object on which the method should be called (this).

If you like it more explicit you can also write a closure manually:

void Start(string url) {
  var that = this; // that get's captured by the closure
  ident = aStaticClass.DoSomethingAndForkThread(url, () => that.callback_when_done());
}
Matthias247
  • 9,836
  • 1
  • 20
  • 29