C# version of java#39;s synchronized keyword?(java的同步关键字的C#版本?)
问题描述
Does c# have its own version of the java "synchronized" keyword?
I.e. in java it can be specified either to a function, an object or a block of code, like so:
public synchronized void doImportantStuff() {
// dangerous code goes here.
}
or
public void doImportantStuff() {
// trivial stuff
synchronized(someLock) {
// dangerous code goes here.
}
}
First - most classes will never need to be thread-safe. Use YAGNI: only apply thread-safety when you know you actually are going to use it (and test it).
For the method-level stuff, there is [MethodImpl]
:
[MethodImpl(MethodImplOptions.Synchronized)]
public void SomeMethod() {/* code *