views:

191

answers:

4

I am designing some immutable classes but I have to have some variables like say .Count to have the total count of the instances. But would having a static variable affect multi-threading?

Because methods like Add, Remove, etc have to update the .Count value. Maybe I should make it lazy property?

A: 

Yes, whenever you update a shared variable in a multi-threaded environment you will need to just wrap those updates in a lock.

rein
+2  A: 

You might want to consider using functions from the Interlocked class, at least in the example you gave.

Promit
So that means in practice, the parallel operations will be slower, right?
Joan Venge
Slower than what?
bdonlan
Slower than a case where the count was an instance (not that it would work), but theoretically.
Joan Venge
+2  A: 

If you're just doing a counter, interlocked operations may be an option as well instead of a lock. MSDN has a nice example of this in the context of a reference count.

bdonlan
+1  A: 

But would having a static variable affect multi-threading?

sure! shared state is affected, by defition, by multi-threading.

Because methods like Add, Remove, etc have to update the .Count value. Maybe I should make it lazy property?

it's better using a class that does an atomic add (like AtomicInteger in java) in order to avoid locks: take a look here

dfa