C# Multi-Threading - Locking
I was a bit confused on the concept of locking in some scenarios. Let me explain开发者_JAVA技巧, suppose I have the following:
private readonly MyClass myObj;
private void Go(object state)
{
// call an instance member of myObj, but does it need to be locked?
myObj.SomeMethod(state);
}
So the question is does myObj need to be locked when calling SomeMethod? It is read-only, however since multiple threads can call the instance method SomeMethod of myObj with varying states will this not cause issues??
Thanks.
The variable is readonly, but the object may be mutable or immutable - and even that doesn't really tell you whether or not it can be used safely from multiple threads.
In other words, it depends on the implementation of MyClass
, and whether you expect Go
to be called from multiple threads referring to the same MyClass
instance. (These days I tend to write classes not to be thread safe, but typically each thread gets its own set of objects to play with - so I'd probably have an instance of the class containing Go
, and an instance of MyClass
, but know that other threads shouldn't be using the same instances.)
It depends, if SomeMethod
is a thread safe method then you don't need locking. Otherwise you may need to use lock.
It's hard to say for certain without more information on what you mean by "varying states", but in general, if a method is only reading from fields that you know won't be changed on other threads, you should be fine without a lock.
If you're only relying on readonly
, though, then that's not good enough, since the object itself may be changing during calls from different threads.
精彩评论