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 ?
Given that you’re not actually using much of the functionality of BackgroundWorker, I would recommend using the TPL for this instead:
That being said, the
workerobject 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 ofBackgroundWorker.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.