I'm passing a System.Action
as a parameter to a method which does some lengthy operation and want to add more stuff to the invocation list after the Action
has been passed:
class Class1
{
private System.Action onDoneCallback;
void StartAsyncOperation(System.Action onDoneCallback)
{
this.onDoneCallback = onDoneCallback;
// do lengthy stuff
}
void MuchLater()
{
this.onDoneCallBack?.Invoke();
}
}
class Class2
{
public System.Action action;
void DoStuff()
{
action += () => print ("a");
new Class1().StartAsyncOperation(action);
}
{
// ... much later in another place but still before StartAsyncOperation ends
action += () => print ("b");
}
}
However, only the the stuff that was added with +=
before passing the Action as parameter is invoked. So, in this example, it will only print "a"
but not "b"
.
This makes me think that System.Action
is copied when it's passed as parameter (like a primitive type e.g. int
would). So, when +=
is done later, it has no effect on the local copy of action
inside SomeAsyncOperation
.
I thought of passing System.Action
with ref
. However, I need to store it as member variable inside Class1
, and I can't make a member variable a ref
!
So, basically, the question is: how do you add more stuff to the invocation list of a callback after that callback has been passed and the lengthy operation is long on its way but hasn't ended yet.
EDIT:
Ended up replacing
new Class1().StartAsyncOperation(action);
with
new Class1().StartAsyncOperation(() => action?.Invoke());
action
, pass() => action()
. – Tetraploid