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.
}
}
This question is related to
c#
java
multithreading
synchronization
static object Lock = new object();
lock (Lock)
{
// do stuff
}
You can use the lock
statement instead. I think this can only replace the second version. Also, remember that both synchronized
and lock
need to operate on an object.
Does c# have its own version of the java "synchronized" keyword?
No. In C#, you explicitly lock
resources that you want to work on synchronously across asynchronous threads. lock
opens a block; it doesn't work on method level.
However, the underlying mechanism is similar since lock
works by invoking Monitor.Enter
(and subsequently Monitor.Exit
) on the runtime. Java works the same way, according to the Sun documentation.
Take note, with full paths the line: [MethodImpl(MethodImplOptions.Synchronized)]
should look like
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]
Source: Stackoverflow.com