348

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.
   }
}
3
  • 3
    The block form requires a reference to lock. In the method form the lock object is implicitly this (or the Class [this.class, not getClass()] for static methods, but don't lock on Classes). Feb 12, 2009 at 13:45
  • 2
    Still not protected ? I always come here because I can't remember that [MethodImpl(MethodImplOptions.Synchronized)] line.
    – Bitterblue
    Mar 17, 2014 at 13:00
  • 1
    I think your 2nd snippet wouldn't compile - it needs to synchronized on something. Oct 16, 2015 at 21:48

5 Answers 5

515

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 */}

This can also be used on accessors (properties and events):

private int i;
public int SomeProperty
{
    [MethodImpl(MethodImplOptions.Synchronized)]
    get { return i; }
    [MethodImpl(MethodImplOptions.Synchronized)]
    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 don't like the implementation of MethodImpl as it locks this or typeof(Foo) - which is against best practice. The preferred option is to use your own locks:

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

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 uses Interlocked updates - so thread-safe without the nasty parts.

This allows more granular usage, and allows use of Monitor.Wait/Monitor.Pulse etc to communicate between threads.

A related blog entry (later revisited).

19
  • @earcam and your question is? That statement is true. The vast majority of classes have no requirement to be thread-safe, will not be tested for thread-safety, and having thread-safety will impact performance. The number of types that genuinely need to worry about threads is very small - intentionally synchronized collections, multiplexers, etc. Nov 8, 2011 at 9:02
  • 6
    I think I should have simply stated; "most classes will never need to be thread-safe" but "all developers must concurrency aware". In retrospect I agree the number is very small (and definitely something you want to get right once in one place, allowing the majority of classes to interact oblivious to their multi-threaded surroundings). Wish I'd deleted the comment quicker =)
    – earcam
    Nov 8, 2011 at 10:34
  • 7
    Marc's linked blog post has a March 2010 follow-up saying that in .NET 4.0, MethodImpl and field-like events now generate good synchronization code, and it is no longer necessary to use your own locks. Jun 3, 2013 at 19:47
  • 2
    A good majority of applications these days are web-based, served with frameworks relying on heavy instance reuse and complex object lifecycle via dependency-injection. The default mindset these days tends to err to the side of thread-safety.
    – Sheepy
    Jan 10, 2015 at 7:11
  • 1
    @Elazar too late now, but for the record: changing the framework is a one-line change to they csproj if you've created it using the .net standard / .net core templates - and regular .net is available, as is multi-targeting. However, the IDE tooling around this is simply terrible - you just need to know what you can change and to what :) Aug 15, 2017 at 22:35
68
static object Lock = new object();

lock (Lock) 
{
// do stuff
}
6
  • 13
    Are you sure you want to declare your lock object as static..?
    – serg10
    Feb 12, 2009 at 20:13
  • 22
    Sure, so every Thread can easily access it without passing references around. Feb 12, 2009 at 21:27
  • 40
    If we are in the context of the asker's question, then we are talking about instance methods. Using static means that if thread 1 calls instance1.DoSomething() and thread 2 calls instance2.DoSomething, the second call will block even though it is a completely different object. thread2's call shouldn't block unless someone is calling DoSomething on the same object. Not saying you are wrong, but saying it is important to understand the effect of using static here, because it may cause poor performance by blocking globally instead of on a per instance basis.
    – AaronLS
    Apr 15, 2013 at 7:03
  • 1
    @AaronLS The static lock if very useful when your object performs actions on a bigger scope than itself. Always happens with web-services for example. Apr 19, 2013 at 12:59
  • 7
    -1 as this is a different behavior than the OP is asking for. This is a class lock, not an instance lock.
    – tster
    Oct 25, 2013 at 18:51
39

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.

3
  • 3
    It doesn't have an equivalent "keyword", but as Marc Gravell's answer above shows, you can synchronize at the method level using the [MethodImpl(MethodImplOptions.Synchronized)] annotation.
    – MindJuice
    Jan 3, 2013 at 19:28
  • 1
    Since Java's synchronized on method is basically synchronized (this.getClass()) wouldn't the similar on C# be lock(typeof(this))? Apr 1, 2017 at 18:56
  • 2
    @SriHarshaChilakapati that's only partially correct, java's synchronized keyword on a method is more like: synchronized(this) , only on a static method it behaves like synchronized(class).
    – bvdb
    Jul 3, 2018 at 12:07
6

Take note, with full paths the line: [MethodImpl(MethodImplOptions.Synchronized)] should look like

[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]

3
  • 3
    or you can just use using System.Runtime.CompilerServices;
    – aloisdg
    Sep 11, 2015 at 13:27
  • I wrote that comment when I didn't yet know about automatically inserting using statements, after having programmed C# for no more than a few days or weeks and I am amazed about those 3 upvotes.
    – ASA
    Sep 11, 2015 at 22:47
  • 1
    You helped at least 3 devs and that's nice :)
    – aloisdg
    Sep 11, 2015 at 23:01
5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.