Alex Rivera | Logout

How to dispose objects having asynchronous methods called?

Asked 2009-06-10T11:09:05.400
16

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 ??

Edit
Report

1 Answer

0

Well, disposing an object is used to kill resources that you don't want held until the GC (eventually) comes and collects your object. Does your dispose method kill anything you need in client_PreloadCompleted?

You could have the object dispose itself, when all expected callbacks have happened: Keep a "reference counter" for each callback you are expecting and decrement that on each callback that happens - check for null at end of callback handler and dispose if so.

Other workaround: Don't worry about IDisposable. GC will collect your object. You probably don't want a callback handler (that might not be fired) to have critical state. It (the callback) should just open any resources it needs when it is called and close them then.

answered 2009-06-10T11:15:35.310

Your Answer