threading and variable scope question

M

Mark Huebner

If I have a class C that contains a private variable (property) V and
private function T and T is executed within C as a separate thread, does
thread T have access to private variable (property) V in the instance of
class C? It appears to but another person has suggested that this is
dangerous and that global variables should be defined in a separate class
with the static type modifer.
 
N

Nicholas Paldino [.NET/C# MVP]

Mark,

The method that is executed doesn't have accessibility changed because
it is running in another thread. So if your thread method T is indeed on C,
then it should have access to all members of that instance of C (if it is an
instance method).

The reason this is dangerous is that if the method T is not the only
method accessing V (which it most likely isn't, otherwise it would be a
variable in the method itself), you need to synchronize access to it. The
easiest way to do this is through the lock statement.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top