Background worker and garbage collection?

c#

Solution

Given that you're not actually using much of the functionality of BackgroundWorker, I would recommend using the TPL for this instead:

private void DownLoadFile(string fileLocation)
{
    Task.Factory.StartNew( () => Download(fileLocation))
        .ContinueWith(t => ReportResult(t.Result), TaskScheduler.FromCurrentSynchronizationContext());
}

That being said, the `worker` object will not be garbage collected once it's running, as the ThreadPool thread itself will keep worker as a "used object". The garbage collector will not be able to collect it until after the completion event handler executes, at which point in time there would be no user code which could reach the instance of `BackgroundWorker`.

In addition, it will likely keep the instance of this class from being garbage collected, as the instance methods (`ReportResults`) used by the closure keep the instance of "this" accessible and not eligible for GC.

Problem

Can I define a background worker in a method ? ``` private void DownLoadFile(string fileLocation){ BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler((obj, args) => { // Will be executed by back ground thread asynchronously. args.Result = Download(fileLocation); }); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((obj, args) => { // will be executed in the main thread. Result r = args.Result as Result; ReportResult(r); }); worker.RunWorkerAsync(fileLocation); } ``` Question: If Download() function takes a long time to download the file, can GC kick in and collect worker object before the RunWorkerCompleted() is executed ?

Original source