Accessing class member variables inside a BackgroundWorker's DoWork event handler, and other Backgro

Posted by Justin on Stack Overflow See other posts from Stack Overflow or by Justin
Published on 2010-03-18T01:36:47Z Indexed on 2010/03/18 1:41 UTC
Read the original article Hit count: 400

Filed under:
|

Question 1

In the DoWork event handler of a BackgroundWorker, is it safe to access (for both reading and writing) member variables of the class that contains the BackgroundWorker? Is it safe to access other variables that are not declared inside the DoWork event handler itself?

Obviously DoWork should not be accessing any UI objects of, say, a WinForms application, as the UI should only be updated from the UI thread. But what about accessing other (not UI-related) member variables?

The reason why I ask is that I've seen the occasional comment come up while Googling saying that accessing member variables is not allowed. The only example I can find at the moment is a comment on this MSDN page, which says:

Note, that the BGW can cause exceptions if it attempts to access or modify class level variables. All data must be passed to it by delegates and events.

And also:

NEVER. NEVER. Never try to reference variables not declared inside of DoWork. It may seem to work at times, but in reality you are just getting lucky.

As far as I know, MSDN itself does not document any restrictions of this kind (although if I'm wrong, I'd appreciate a link). But comments like these do seem to pop up every now and again.

(Of course if DoWork does access/modify a member variable that could be accessed/modified by the main thread at the same time, it is necessary to synchronise access to that field, eg by using a locking object. But the above quotes seem to require a blanket ban of accessing member variables, rather than just synchronising access!)

Question 2

To make this into a more general question, are there any other (not documented?) restrictions that users of the BackgroundWorker should be aware of, aside from the above? Any "best practices", perhaps?

© Stack Overflow or respective owner

Related posts about backgroundworker

Related posts about .NET