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 ?
Background garbage collection removes allocation restrictions imposed by concurrent garbage collection, because ephemeral garbage collections can occur during background garbage collection. Background garbage collection can remove dead objects in ephemeral generations.
The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running.
Garbage collection ensures that a program does not exceed its memory quota or reach a point that it can no longer function. It also frees up developers from having to manually manage a program's memory, which, in turn, reduces the potential for memory-related bugs.
Garbage collection is the process in which programs try to free up memory space that is no longer used by objects. Garbage collection is implemented differently for every language. Most high-level programming languages have some sort of garbage collection built in.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With