views:

474

answers:

3

Would this be a proper way to dispose of a BackGroundWorker? I'm not sure if it is necesary to remove the events before calling .Dispose(). Also is calling .Dispose() inside the RunWorkerCompleted delegate ok to do?

public void RunProcessAsync(DateTime dumpDate)
{
    BackgroundWorker worker = new BackgroundWorker();
    worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
    worker.DoWork += new DoWorkEventHandler(worker_DoWork);
    worker.RunWorkerAsync(dumpDate);
}

void worker_DoWork(object sender, DoWorkEventArgs e)
{
    // Do Work here
}

void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    worker.RunWorkerCompleted -= new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
    worker.DoWork -= new DoWorkEventHandler(worker_DoWork);
    worker.Dispose();
}
A: 

Yes, this appears proper. Of course, disposable objects are better handled with using blocks, but you don't have that option here.

I usually create my background handers with form lifetimes, reuse them, and let the designer code handle disposal on form close. Less to think about.

Michael Petrotta
That is how I have always done it in the past. Although I did not realize that dropping a BackGroundWorker on a WinForm during design time added the BGW to the list of object that would be Disposed when the Form is disposed. I generally had created the BGW programmatically.
galford13x
+3  A: 

BackgroundWorker derives from Component. Component implements the IDisposable interface. That in turn makes BackgroundWorker inherit the Dispose() method.

Deriving from Component is a convenience for Windows Forms programmers, they can drop a BGW from the toolbox onto a form. Components in general are somewhat likely to have something to dispose. The Windows Forms designer takes care of this automatically, look in the Designer.cs file for a Form for the "components" field. Its auto-generated Dispose() method calls the Dispose() method for all components.

However, BackgroundWorker doesn't actually have any member that requires disposing. It doesn't override Dispose(). Its base implementation, Component.Dispose(), only makes sure that the component is removed from the "components" collection. And raise the Disposed event. But doesn't otherwise dispose anything.

Long story short: if you dropped a BGW on a form then everything is taken care of automatically, you don't have to help. If you didn't drop it on a form then it isn't an element in a components collection and nothing needs to be done.

You don't have to call Dispose().

Hans Passant
Personally I do like to follow the policy of calling `Dispose` if present in the event that the implementation of the class actually changes...
Paul Kohler
I can't argue with that. But prefer always thinking: "what kind of object could be wrapped by a class that would require disposing?" And have a look. I have trouble writing code that makes no sense and don't buy into the notion that it will make sense some day. It works the other way around too: the Thread class really has disposable objects but doesn't implement IDisposable. To each his own.
Hans Passant
@nobugz: Just so I understand. A BGW doesn't need to be disposed since it has nothing to Dispose? I had read sometime that if events are not removed they can continue to hang out preventing freed resources when an object that relies on them are disposed. Is this never the case?
galford13x
@galford: it is technically possible for an event handler wired to a BGW's event to prevent a form object from being garbage collected. That never happens in practice because you always make the BGW object a member of the form. They'll get both garbage collected at the same time.
Hans Passant
@nobugz: I see, then my current implementation is lacking as I need to add this.Components.Add(BGW), and also make the BGW a persistant object within the form rather than createing the BGW each time the RunProcessAsync method is called. That makes sense. The BGW isn't memory intensive anyway, and recreating it each time just uses more cpu than is needed.
galford13x
A: 

If it's on a "WinForms" Form let the container take care of it (see the generated Dispose code in the Form.Designer.xyz file)

In practice I have found that you may need to create an instance of the container and add the worker (or other companent) to it, if anyone knows a more official way to do this yell out!!

PK :-)

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        // watch the disposed event....
        backgroundWorker1.Disposed += new EventHandler(backgroundWorker1_Disposed);

        // try with and without the following lines
        components = new Container();
        components.Add(backgroundWorker1);
    }

    void backgroundWorker1_Disposed(object sender, EventArgs e)
    {
        Debug.WriteLine("backgroundWorker1_Disposed");
    }

//... from the Designer.xyz file ...

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

}
Paul Kohler