Coder Perfect

Is there a C# equivalent to Java’s synchronized keyword?


Is there a c# equivalent to the Java “synchronized” keyword?

In Java, it can be applied to a function, an object, or a block of code, for example:

public synchronized void doImportantStuff() {
   // dangerous code goes here.


public void doImportantStuff() {
   // trivial stuff

   synchronized(someLock) {
      // dangerous code goes here.

Asked by Soraz

Solution #1

To begin with, most classes will never be thread-safe. Employ YAGNI: only use thread-safety when you’re sure you’ll be using it (and test it).

[MethodImpl]: [MethodImpl]: [MethodImpl]: [MethodImpl]: [Method

public void SomeMethod() {/* code */}

Accessors (properties and events) can also be utilized in this way:

private int i;
public int SomeProperty
    get { return i; }
    set { i = value; }

Note that field-like events are synchronized by default, while auto-implemented properties are not:

public int SomeProperty {get;set;} // not synchronized
public event EventHandler SomeEvent; // synchronized

Personally, I dislike MethodImpl’s approach because it locks this or typeof(Foo), which is not recommended. Using your own locks is the best option:

private readonly object syncLock = new object();
public void SomeMethod() {
    lock(syncLock) { /* code */ }

Note that the locking implementation for field-like events is compiler-dependent; in older Microsoft compilers, it’s a lock(this) / lock(Type) – but in more current compilers, it’s Interlocked updates – thus thread-safe without the nasty parts.

This allows for more precise usage and the use of Monitor. Wait/Monitor. To communicate across threads, use pulses, etc.

A similar post on the blog (later revisited).

Answered by Marc Gravell

Solution #2

static object Lock = new object();

lock (Lock) 
// do stuff

Answered by Jan Gressmann

Solution #3

No. In C#, you explicitly lock resources across asynchronous threads that you want to work on synchronously. The lock method opens a block, however it does not operate on the method level.

However, because lock works by invoking Monitor, the basic process is similar. On the runtime, enter (and then Monitor.Exit). Java works the same way, according to the Sun documentation.

Answered by Konrad Rudolph

Solution #4

Keep in mind that when using complete paths, the line [MethodImpl(MethodImplOptions.Synchronized)] should look like this:


Answered by ASA

Solution #5

Instead, you can use the lock statement. This, I believe, can only be used to replace the second version. Also keep in mind that both synchronized and lock must be applied to an object.

Answered by James

Post is based on