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

  • Home
  • SEARCH
  • 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 3499134
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T12:34:29+00:00 2026-05-18T12:34:29+00:00

I am observing a strange bug in some of my code which I suspect

  • 0

I am observing a strange bug in some of my code which I suspect is tied to the way closing a form and background workers interact.

Here is the code potentially at fault:

var worker = new BackgroundWorker();
    worker.DoWork += (sender, args) => {
        command();
    };
    worker.RunWorkerCompleted += (sender, args) => {
        cleanup();
        if (args.Error != null)
            MessageBox.Show("...", "...", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    };
    worker.RunWorkerAsync();

This code is executed in a method in a form, when a button is pressed.
command() is slow, it may take a few seconds to run.

The user presses a button which executes the code above to be executed. Before it is done, the form is closed.

The problem is that calling cleanup() sometimes raises ObjectDisposedException. I say “sometimes”, because this never happens on my computer. If the form is closed before command() is done, the handler I registered for RunWorkerCompleted is not executed. On another computer, the handler is called once out of hundred times. On a coworker’s computer, it’s almost always called. Apparently, the probability of execution of the handler rises with the age/slowness of the computer.

First question:

Is this the expected behaviour of BakgroundWorker? I would not expect it to know anything about the form, as there is nothing I can see that ties the form “this” with “worker”.

Second question:

How should I go about fixing that problem?

Possible solutions I’m considering:

  1. Test if (!this.IsDisposed) before calling cleanup(). Is that enough, or can the form be disposed while cleanup is being executed?
  2. Wrap the call to cleanup() in a try {} catch (ObjectDisposedException). I don’t like that kind of approach too much, as I may be catching exceptions that were raised due to some other unrelated bug in cleanup() or one of the methods it calls.
  3. Register a handler for IsClosing and delay or cancel closing until the handler for RunWorker Completed has run.

Additional information that may be relevant: code from command() will cause updates to be done to GUI objects in “this”. Such updates are performed via calls to this F# function:

/// Run a delegate on a ISynchronizeInvoke (typically a Windows.Form).
let runOnInvoker (notification_receiver : ISynchronizeInvoke) excHandler (dlg : Delegate) args =
    try
        let args : System.Object[] = args |> Seq.cast |> Array.ofSeq
        notification_receiver.Invoke (dlg, args) |> ignore
    with
        | :? System.InvalidOperationException as op ->
            excHandler(op)
  • 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-18T12:34:30+00:00Added an answer on May 18, 2026 at 12:34 pm

    The exceptions you mentioned do not have any connection to BackgroundWorker, other than the fact that one thread (the worker) tries to access controls which have been disposed by another thread (the UI).

    The solution I would use is to attach an event handler to the Form.FormClosed event to set a flag that tells you the UI has been torn down. Then, then RunWorkerCompleted handle will check to see if the UI has been torn down before trying to do anything with the form.

    While this approach will probably work more reliably than checking IsDisposed if you are not disposing the form explicitly, it does not provide a 100% guarantee that the form will not be closed and/or disposed just after the cleanup code has checked the flag and found that it is still there. This is the race condition you yourself mention.

    To eliminate this race condition, you will need to synchronize, for example like this:

    // set this to new object() in the constructor
    public object CloseMonitor { get; private set; }
    
    public bool HasBeenClosed { get; private set; }
    
    private void Form1_FormClosed(object sender, FormClosedEventArgs e) {
        lock (this.CloseMonitor) {
            this.HasBeenClosed = true;
            // other code
        }
    }
    

    and for the worker:

    worker.RunWorkerCompleted += (sender, args) => {
        lock (form.CloseMonitor) {
            if (form.HasBeenClosed) {
                // maybe special code for this case
            }
            else {
                cleanup();
                // and other code
            }
        }
    };
    

    The Form.FormClosing event will also work fine for this purpose, you can use whichever of the two is more convenient if it makes a difference.

    Note that, the way this code is written, both event handlers will be scheduled for execution on the UI thread (this is because WinForms components use a single-threaded apartment model) so you would actually not be affected by a race condition. However, if you decide to spawn more threads in the future you might expose the race condition unless you do use locking. In practice I have seen this happen quite often, so I suggest synchronizing anyway to be future-proof. Performance will not be affected as the sync only happens once.

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

Sidebar

Related Questions

I am trying to get key-value-observing to work for an NSMutableArray. Below is the

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.