Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# version of java's synchronized keyword?

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.    } } 
like image 497
Soraz Avatar asked Feb 12 '09 13:02

Soraz


People also ask

Bahasa C digunakan untuk apa?

Meskipun C dibuat untuk memprogram sistem dan jaringan komputer namun bahasa ini juga sering digunakan dalam mengembangkan software aplikasi. C juga banyak dipakai oleh berbagai jenis platform sistem operasi dan arsitektur komputer, bahkan terdapat beberepa compiler yang sangat populer telah tersedia.

Apakah C termasuk bahasa pemrograman?

Bahasa C atau dibaca “si” adalah bahasa pemrograman tingkat tinggi dan general-purpose yang digunakan dalam sehari-hari. Maksud dari general-purpose adalah bisa digunakan untuk membuat program apa saja.

Apa yang dimaksud dengan huruf C?

C adalah huruf ketiga dalam alfabet Latin. Dalam bahasa Indonesia, huruf ini disebut ce (dibaca [tʃe]).


1 Answers

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).

like image 100
Marc Gravell Avatar answered Sep 24 '22 19:09

Marc Gravell