BackgroundWorker and instance variables

One thing that has always confused me is how BackgroundWorker seems to have thread-safe access to instance variables of the surrounding class.

Given the base class:

public class BackgroundProcessor
{
    public List<int> Items { get; private set; }

    public BackgroundProcessor(IEnumerable<int> items)
    {
        Items = new List<int>(items);
    }

    public void DoWork()
    {
        BackgroundWorker worker = new BackgroundWorker();
        worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
        worker.DoWork += new DoWorkEventHandler(worker_DoWork);
        worker.RunWorkerAsync();
    }

    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        var processor = new ProcessingClass();

        processor.Process(this.Items); //Accessing the instance variable
    }

    void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        //Stuff goes here
    }
}

Am I mistaken in my assumption that the call processor.Process(this.Points);is a thread-safe call? How can I get cross flow access violation?

I'm sure this is obvious, but it always confused me.

+3
source share
2 answers

-, . . , , . , . , ( , , USER), .

- , . - . , . , , , , , , . , , , .

+6

- , .

, , .

0

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


All Articles