Rodney Burton
Rodney Burton

Reputation: 447

C# async callback on disposed form

Quick question: One of my forms in my winform app (c#) makes an async call to a WCF service to get some data. If the form happens to close before the callback happens, it crashes with an error about accessing a disposed object. What's the correct way to check/handle this situation? The error happens on the Invoke call to the method to update my form, but I can't drill down to the inner exception because it says the code has been optimized.

The Code:

  public void RequestUserPhoto(int userID)
        {
            WCF.Service.BeginGetUserPhoto(userID,
                new AsyncCallback(GetUserPhotoCB), userID);
        }

    public void GetUserPhotoCB(IAsyncResult result)
    {
        var photo = WCF.Service.EndGetUserPhoto(result);
        int userID = (int)result.AsyncState;
        UpdateUserPhoto(userID, photo);
    }

    public delegate void UpdateUserPhotoDelegate(int userID, Binary photo);
    public void UpdateUserPhoto(int userID, Binary photo)
    {
        if (InvokeRequired)
        {
            var d = new UpdateUserPhotoDelegate(UpdateUserPhoto);
            Invoke(d, new object[] { userID, photo });
        }
        else
        {
            if (photo != null)
            {
                var ms = new MemoryStream(photo.ToArray());
                var bmp = new System.Drawing.Bitmap(ms);
                if (userID == theForm.AuthUserID)
                {
                    pbMyPhoto.BackgroundImage = bmp;
                }
                else
                {
                    pbPhoto.BackgroundImage = bmp;
                }
            }
        }
    }

UPDATE:

I still don't know where to go with this. What I really need here is a design pattern for making WCF async service calls from a win form that is elegant at handling form closes before the async call can return. The user is able to click the X on the form, or any form, at any time. The problem is much larger than the single example I shown above. My app actually makes hundreds of WCF calls, and I'm trying to figure out how to handle these gracefully, and in a consistent way throughout my application. For example, if I have to add a 100 lines of codes with ManualResetEvents or background workers, or mutexes, or whatever, for each WCF call just so it won't bomb my app, that's going to introduce a lot of room for error. What I need is a clean way to call a service asyncronously, and then convert it to a one-way call if the form happens to close. In other words, let the service finish running, but I don't care what the results are, and don't call the callback, because it isn't there anymore.

Upvotes: 2

Views: 3843

Answers (5)

Rodney Burton
Rodney Burton

Reputation: 447

I got a lot of good comments on this question, but no good pattern that I can use throughout my application. I am posting here what I ended up doing as my answer, and hopefully it will help someone else down the road.

The WCF proxy that is automatically generated creates sync call methods, async methods using the begin/end pattern, and event based delegates using a Completed event. The example I posted above in my original question used the Begin/End pattern. The problem is that when the callback is made, you will have to do an Invoke to access your UI thread. If that UI thread is not there anymore (I.E. the user closed the window), you've got problems. The new event based pattern, automatically finds its way back to the UI thread, and from my testing, I have not been able to make it crash by closing before the service can complete. I guess the proxy is smart enough to NOT call the completed handler if the memory address does not exist? Or maybe it hangs onto a memory address to the handler, so it won't be garbage collected? So all you have to do is add a Completed event handler, fire off your call etc, servicenameAsync(), and wait for it to return to your handler (on the UI thread). I also, just to make sure, wrapped my completed handlers in try/catch blocks to handle ObjectDisposedExceptions, if any.

The main thing now: IT DOESN'T CRASH.

One gotcha (at least for me)... I was using a singleton pattern to access my WCF service. The problem with this is that it creates a static reference to your WCF proxy, used throughout your entire application. Sounds convenient, but when you are appending event handlers to the Completed events right before you make your async call, then those can get duplicated, triplicated, etc. Every time you make the call, you add ANOTHER completed event handler in addition to the one already added to your static WCF proxy. To solve this, I started declaring a new proxy clients for each call, or if multiple calls are not made per winform class, per each winform. If anyone has any comments on this or a better way, PLEASE let me know! The biggest problem with the singleton pattern is that if you have multiple windows open at the same time (different classes) that call the same async method, but you want them to return to different Completed handlers, you can't do that.

Upvotes: 0

Brett Veenstra
Brett Veenstra

Reputation: 48494

You're giving the callback an address to hit when the operation is done. The address is invalid when you close the form and hence you're getting this error. You need to build in a way of determining if you have an outstanding call before allowing your form to close.

I'd research the BackgroundWorker class. I'm sure you can still setup a crash by closing your form before the callback has fired, but with the BackgroundWorker, you should be able to interrogate it's status and handle your situation more gracefully.

You should not let your form close while the Async call is still active. Using BackgroundWorker, you can easily determine if the Async call is active.

Upvotes: 0

Doobi
Doobi

Reputation: 4842

Create a flag, something like "IsWaiting" as a ManualResetEvent (or even a simple bool), set it to true and only set it to false when your async result returns.

In your class dispose method put in a check for the flag, and only dispose the object once the flag has cleared. (Put in a timeout, just in case there's an error)

Upvotes: 0

Dr. Wily's Apprentice
Dr. Wily's Apprentice

Reputation: 10280

I believe that there is an IsDisposed property on the Form object. You could check that property before calling Invoke.

Upvotes: 0

Dan Byström
Dan Byström

Reputation: 9244

public void UpdateUserPhoto(int userID, Binary photo)
{
  if ( Disposed || !IsHandleCreated )
    return;
  if (InvokeRequired)
  ...

Upvotes: 1

Related Questions