Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 939047
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T21:43:37+00:00 2026-05-15T21:43:37+00:00

Quick question: One of my forms in my winform app (c#) makes an async

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T21:43:38+00:00Added an answer on May 15, 2026 at 9:43 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.