Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First - most classes will never need to be thread-safe. Use <a href="http://en.wikipedia.org/wiki/You_aren&#39;t_gonna_need_it" rel="noreferrer">YAGNI</a>: only apply thread-safety when you know you actually are going to use it (and test it).</p> <p>For the method-level stuff, there is <code>[MethodImpl]</code>:</p> <pre><code>[MethodImpl(MethodImplOptions.Synchronized)] public void SomeMethod() {/* code */} </code></pre> <p>This can also be used on accessors (properties and events):</p> <pre><code>private int i; public int SomeProperty { [MethodImpl(MethodImplOptions.Synchronized)] get { return i; } [MethodImpl(MethodImplOptions.Synchronized)] set { i = value; } } </code></pre> <p>Note that field-like events <em>are</em> synchronized by default, while auto-implemented properties <em>are not</em>:</p> <pre><code>public int SomeProperty {get;set;} // not synchronized public event EventHandler SomeEvent; // synchronized </code></pre> <p>Personally, I don't like the implementation of <code>MethodImpl</code> as it locks <code>this</code> or <code>typeof(Foo)</code> - which is against best practice. The preferred option is to use your own locks:</p> <pre><code>private readonly object syncLock = new object(); public void SomeMethod() { lock(syncLock) { /* code */ } } </code></pre> <p>Note that for field-like events, the locking implementation is dependent on the compiler; in older Microsoft compilers it is a <code>lock(this)</code> / <code>lock(Type)</code> - however, <a href="http://marcgravell.blogspot.co.uk/2010/03/revisited-fun-with-field-like-events.html" rel="noreferrer">in more recent compilers it uses <code>Interlocked</code></a> updates - so thread-safe without the nasty parts.</p> <p>This allows more granular usage, and allows use of <code>Monitor.Wait</code>/<code>Monitor.Pulse</code> etc to communicate between threads.</p> <p>A related <a href="http://marcgravell.blogspot.com/2009/02/fun-with-field-like-events.html" rel="noreferrer">blog entry</a> (later <a href="http://marcgravell.blogspot.co.uk/2010/03/revisited-fun-with-field-like-events.html" rel="noreferrer">revisited</a>).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload