I am trying to use a reference that is defined outside of a delegate I have defined like so (simplified version of what I am dealing with):
private void DoStuff(int objectKey)
{
MyObject myObject;
if (this.concurrentDictionary.TryRemove(objectKey, out myObject))
{
Action<IList<IEvent>> eventsCompletedDelegate (eventList) =>
{
// Do work ...
myObject.DoSomething();
};
ExecuteStuffAsync(eventsCompletedDelegate);
}
}
The problem is that eventsCompletedDelegate is executed asynchronously (some time after ExecuteStuffAsync is called). I want to be able to access myObject from within the closure but by the time the delegate is invoked the local myObject reference will be disposed. Is there a way to pass in myObject into the delegate so that it will still be available by the time the delegate is invoked?