I have this object PreloadClient which implements IDisposable, I want to dispose it, but after the asynchronous methods finish their call… which is not happening
private void Preload(SlideHandler slide)
{
using(PreloadClient client = new PreloadClient())
{
client.PreloadCompleted += client_PreloadCompleted;
client.Preload(slide);
}
// Here client is disposed immediately
}
private void client_PreloadCompleted(object sender, SlidePreloadCompletedEventArgs e)
{
// this is method is called after a while,
// but errors are thrown when trying to access object state (fields, properties)
}
So, any ideas or work arounds ??
You shouldn’t use the
usingconstruct, but rather dispose your objects when they are no longer needed:in this case, you have to dispose all clients when disposing the main class:
Note that this implementation is not thread safe
_activeClientslist must be made thread-safe, as yourPreloadCompletedmethod is called from a different threadtry/finallyblock inside your event handler, to make sure that the object gets disposed in all cases