I have a Register Callback method on a Game class that objects can register a callback with for when the game is shutting down.
public void RegisterAsyncShutdownCallback(Func<Task> callback)
{
if (this.asyncShutdownCallbacks.Contains(callback))
{
return;
}
this.asyncShutdownCallbacks.Add(callback);
}
When the game shuts down, i invoke the callbacks.
public virtual async Task ShutdownGame()
{
var callbackTasks = new List<Task>();
foreach (var callback in this.asyncShutdownCallbacks)
{
callbackTasks.Add(callback());
}
// Invoke all of the asynchronous callbacks first.
await Task.WhenAll(callbackTasks);
}
My question is, what if the owner of one of these callbacks becomes null, because the monster dies or the item was set to null etc. Am I holding a strong reference to the callback owner? If so, is it better practice to provide a unregister method or should I wrap them in a WeakReference?
The engine is using callbacks in place of events so I can perform async operations in player, monster, battle code etc. So a lot of my objects have this RegisterCallback style of method, and invokes callbacks when certain events happen within the object. If I am holding a strong reference, I'd prefer to hold a weak reference and self clean up rather than rely on objects properly unregistering. The engine provides an API that lets 3rd party users create plugins and register callbacks. I don't want to rely on the devs properly unregistering objects if I can control it within the engine itself.