Search code examples
c#constructorbackgroundworker

During construction, pass this to RunWorkerAsync


I have this code

public class MyClass
{
    BackgroundWorker worker;
    /* ... */
    public MyClass()
    {
        worker = new BackgroundWorker();
        worker.DoWork += DoWhatever;
        worker.RunWorkerAsync(this);
        /* Some other code */
    }
    internal static void DoWhatever(object sender, DoWorkEventArgs e) 
    {
        MyClass thingy = (MyClass)e.Argument; 
        /* ... */ 
    }
}

There I send the own instance to the worker. Could this cause any kind of thread-wise problems, or the code inside DoWhatever will wait until the instance is completely instantiated?

Edit: As clarified on the coments of the accepted answer, race-conditions may arise. This is not thread safe per-se, but if RunWorkerAsync is the last instruction then the constructor is thread safe


Solution

  • Passing an object reference is safe by itself. But indeed the constructor might not be completed when DoWhatever starts. There is no mechanism that magically waits for a constructor to finish until some other unrelated method can start. BackgroundWorker has no connection to whatever code is calling it. It cannot find out even if it wanted to.