I have this object PreloadClient which implements IDisposable, I want to dispose it, but after the asynchronous methods finish their call... which
You shouldn't use the using construct, but rather dispose your objects when they are no longer needed:
// keep a list of strong references to avoid garbage collection,
// and dispose them all in case we're disposing the encapsulating object
private readonly List _activeClients = new List();
private void Preload(SlideHandler slide)
{
PreloadClient client = new PreloadClient();
_activeClients.Add(client);
client.PreloadCompleted += client_PreloadCompleted;
client.Preload(slide);
}
private void client_PreloadCompleted(object sender,
SlidePreloadCompletedEventArgs e)
{
PreloadClient client = sender as PreloadClient;
// do stuff
client.PreloadCompleted -= client_PreloadCompleted;
client.Dispose();
_activeClients.Remove(client);
}
in this case, you have to dispose all clients when disposing the main class:
protected override Dispose(bool disposing)
{
foreach (PreloadClient client in _activeClients)
{
client.PreloadCompleted -= client_PreloadCompleted;
client.Dispose();
}
_activeClients.Clear();
base.Dispose(disposing);
}
Note that this implementation is not thread safe
_activeClients list must be made thread-safe, as your PreloadCompleted method is called from a different threadtry/finally block inside your event handler, to make sure that the object gets disposed in all cases