Fields are global to all threads of a method running in a class?

  • Thread starter Thread starter MrFile
  • Start date Start date
M

MrFile

C#.Net question for everyone

I have a class that has a method that i run async from the Form.

This class has one field string called log. I need this since i have
an event that can write to it sometimes, and not only my async method.

Now im noticing this log seems to be updated by both of the running
threads. Is there any way to resolve this without locking the log
variable and therefore causing my thread to be locked up as well?
 
MrFile,

You will have to use the lock statement or the Monitor class (which is
what the lock statement uses) in order to protect access to this variable.
Whenever you read or write from this variable, it basically has to be
protected (since it is coming in on two separate threads). Locking the
access doesn't mean that it will deadlock, it just means it will block
access to that variable for the duration of what you are trying to do. As
long as you don't perform some very lenghty operations in the lock segment,
or call Enter on the Monitor class without calling Exit, you should be fine.

Hope this helps.
 
MrFile said:
C#.Net question for everyone

I have a class that has a method that i run async from the Form.

This class has one field string called log. I need this since i have
an event that can write to it sometimes, and not only my async method.

Now im noticing this log seems to be updated by both of the running
threads. Is there any way to resolve this without locking the log
variable and therefore causing my thread to be locked up as well?

It's not entirely clear what you mean, but there are two golden rules
which sound like they're important in this situation:

1) Never update the UI from any thread other than the UI thread
2) Never access shared data without locking it

I would suggest not locking the field itself, but locking another
object whose use is purely for locking purposes.

If you want each thread to have its own independent copy of a variable,
you might like to look at ThreadStaticAttribute.
 
Hi MrFile,

How Nicholas and Jon said you have to protected the data that can be
accessed from more than one thread. The other way of protecting a variable
is to update it form only one thread. In other words when you want to update
the variable let this work to be done by one and only one thread. The UI
threads are easier to let do something. So if you don't want to block your
worker threads until updating the filed (however I don't think you should
have problems with that as long as it won't happen all the time and this
operation should be pretty quick) let an UI thread do it. Call some
control's BeginInvoke method and send a delegate to a method that will do
the actual update.
 
Back
Top