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]:This can also be used on accessors (properties and events):
Note that field-like events are synchronized by default, while auto-implemented properties are not:
Personally, I don’t like the implementation of
MethodImplas it locksthisortypeof(Foo)– which is against best practice. The preferred option is to use your own locks:Note that for field-like events, the locking implementation is dependent on the compiler; in older Microsoft compilers it is a
lock(this)/lock(Type)– however, in more recent compilers it usesInterlockedupdates – so thread-safe without the nasty parts.This allows more granular usage, and allows use of
Monitor.Wait/Monitor.Pulseetc to communicate between threads.A related blog entry (later revisited).