问题
what is better? is there any difference in runtime between the two options?
回答1:
There is no runtime difference between locking a static and locking an instance member. However, it can break your code if you use an instance lock and are updating a static.
class Broken {
static int myCounter;
object synch = new object();
void SomeMethod()
{
lock (synch) { // BAD
++myCounter;
}
}
}
回答2:
Huh? I thought it should depend on what you are locking for. If you are trying to lock a non-static object, it should be locking non-static object. By the way, you might want to investigate on what you are trying to do, most of the time, there are already thread safe objects built-in language.
回答3:
Why are you locking a non-static method ? You typically only need synchronization around access to a shared resource, i.e. one that will be shared among all threads. You wouldn't do this with an instance method, you'd want a singleton.
来源:https://stackoverflow.com/questions/6567567/c-sharp-lock-lock-instance-member-vs-lock-static-member