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.Items); //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.
It's not thread-safe, it just looks that way. You only get the cross-thread exception for GUI controls. There is a hard requirement that GUI controls only be accessed from the thread that created them. So the framework takes the time to check for calls from other threads. Note that this is actually orthogonal to synchronization issues (at least from our point of view, not from the point of view of the USER subsystem) as you could still use locks to prevent multiple threads from accessing a control at the same time and still get a cross-thread violation.
Since the member variable is not a GUI control, there is no check for cross-thread calls, nor is there a check for race conditions. You have to do that yourself with locking or some other mechanism. You will get no exception unless the collection classes get corrupted. I don't believe they are thread-safe, but I'm not sure what that ends up meaning, nor have I ever shared those kinds of variables between threads running at the same time, so I haven't actually had the problem. Suffice it to say, it's better to do the right thing than to hope that the collection classes magically work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With