BackgroundWorker and instance variables
Posted
by
Alastair Pitts
on Stack Overflow
See other posts from Stack Overflow
or by Alastair Pitts
Published on 2010-12-21T05:27:43Z
Indexed on
2010/12/21
5:31 UTC
Read the original article
Hit count: 303
One thing that's always confused me is how a BackgroundWorker seems to have thread-safe access to the instance variables of the surrounding class.
Given a basic 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.Points); //Accessing the instance variable
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//Stuff goes here
}
}
Am I erroneous in my assumption the the call to processor.Process(this.Points);
is a thread-safe call? How don't I get a cross-thread access violation?
I'm sure it's obvious, but it always has confused me.
© Stack Overflow or respective owner