When my BackgroundWorker instance is garbage collected

consider this code block

public void ManageInstalledComponentsUpdate()
        {
            IUpdateView view = new UpdaterForm();
            BackgroundWorker worker = new BackgroundWorker();
            Update update = new Update();
            worker.WorkerReportsProgress = true;
            worker.WorkerSupportsCancellation = true;
            worker.DoWork += new DoWorkEventHandler(update.DoUpdate);
            worker.ProgressChanged += new ProgressChangedEventHandler(view.ProgressCallback);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(view.CompletionCallback);            
            worker.RunWorkerAsync();
            Application.Run(view as UpdaterForm);     
        }

Everything works fine, but I want to understand why objects (work, view and update) do not receive garbage collection

+3
source share
3 answers

The number of threads as root objects; I don't know exactly how BackgroundWorker works, but it seems likely that the primary thread method will have access to the state on the working instance; as such, the workflow itself will support the BackgroundWorker instance until (at least) the thread completes.

; , () ; , / / .

[] ; ( ) "" "" ( ), . , , "" "", . , "SomeTarget", : (.. ).

Re, , : ; , " " :

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
class Demo : Form
{
    class ChattyWorker : BackgroundWorker
    {
        ~ChattyWorker()
        {
            Console.WriteLine("Worker finalized");
        }
    }
    class SomeTarget
    {
        ~SomeTarget()
        {
            Console.WriteLine("Target finalized");
        }
        public SomeTarget()
        {
            Console.WriteLine("Target created");
        }
        public void Foo(object sender, EventArgs args)
        {
            Console.WriteLine("Foo");
        }
    }
    static void Collect(object sender, EventArgs args)
    {
        Console.WriteLine("Collecting...");
        GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
    }
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        timer.Interval = 100;
        timer.Tick += Collect;
        timer.Start();

        ChattyWorker worker = new ChattyWorker();
        worker.RunWorkerCompleted += new SomeTarget().Foo;
        worker.DoWork += delegate
        {
            Console.WriteLine("Worker starting");
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(250);
                Console.WriteLine(i);
            }
            Console.WriteLine("Worker exiting");
        };
        worker.RunWorkerAsync();
    }
    [STAThread]
    static void Main()
    { // using a form to force a sync context
        Application.Run(new Demo());
    }
}
+7

- , , "".

ComplitionCallback .

0

Those local variable objects are stored until the function exits, i.e. when the form comes out. Therefore, reset them before calling Run or move them to a different context.

public void ManageInstalledComponentsUpdate() {
    UpdaterForm form = new UpdaterForm();
    FireAndForgetWorker( form );
    Application.Run( form );  //does not return until form exits
}

void FireAndForgetWorker( IUpdateView view ) {
    BackgroundWorker worker = new BackgroundWorker();
    Update update = new Update();
    worker.WorkerReportsProgress = true;
    worker.WorkerSupportsCancellation = true;
    worker.DoWork += new DoWorkEventHandler(update.DoUpdate);
    worker.ProgressChanged += new ProgressChangedEventHandler(view.ProgressCallback);
    worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(view.CompletionCallback);
    worker.RunWorkerAsync();
}

Note for vsick:

Try to run the following program, you will be surprised that x lives forever.

using System;

class FailsOnGarbageCollection  
{ ~FailsOnGarbageCollection() { throw new NotSupportedException(); } }

class Program{
    static void WaitForever() { while (true) { var o = new object(); } }

    static void Main(string[] args)
    {
        var x = new FailsOnGarbageCollection();
        //x = null; //use this line to release x and cause the above exception
        WaitForever();
    }
}
-1
source

Source: https://habr.com/ru/post/1698805/


All Articles