Question 1
In the DoWork event handler for BackgroundWorker, is it safe to access (read and write) the member variables of the class containing BackgroundWorker? Is it safe to access other variables that are not declared inside the DoWork event handler itself?
Obviously, DoWork should not access any user interface objects, say, a WinForms application, since the user interface should only be updated from the user interface stream. But what about accessing other (non-UI) member variables?
The reason I ask is because I saw a random comment when Googling says that access to member variables is not allowed. The only example I can find at the moment is a comment on this MSDN page that says:
Note that BGW can throw exceptions if it tries to access or change class level variables. All data must be transmitted to him by delegates and events.
And:
NEVER. NEVER. Never try to reference variables that are not declared inside DoWork. It seems to work from time to time, but in fact you are just lucky.
As far as I know, MSDN itself does not document any restrictions of this kind (although if I am mistaken, I would appreciate the link). But such comments seem to appear from time to time.
(Of course, if DoWork accesses / changes a member variable that can be accessed / changed at the same time, you need to synchronize access to this field, for example, using a lock object. Quotes seem to require a complete ban on access to member variables , not just sync access!)
Question 2
To make this a more general question, are there any other (not documented?) Restrictions that BackgroundWorker users should be aware of beyond the above? Any "best practices" perhaps?
source share