Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

multithreading - What is a thread-safe way to read/write a C# property in a class?

I am new to C#. In Java, I can make read/write of a Java class member by having 'synchronized' keyword in the setter/getter method.

Can you please tell me what is the right way to do the same in C#? In C# there is no synchronized keyword. Should I use '[MethodImpl(MethodImplOptions.Synchronized)] annotation' mentioned in C# version of java's synchronized keyword??

Or use Monitor.Enter (and subsequently Monitor.Exit)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use Monitor.Enter/Exit (or lock - a syntactic sugar for Monitor) with private object _lock = new object() field.

Don't use MethodImplOptions.Synchronized. It locks on this, so it's possible that some other code will lock on the same instance causing deadlocks.

Locking on the instance or on the type, as with the Synchronized flag, is not recommended for public types, because code other than your own can take locks on public types and instances. This might cause deadlocks or other synchronization problems.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...