Creating Guideline threadsafe Properties

One of my classes has a property of type Guid. This property can be read and written simultaneously by multiple threads. I get the impression that reading and writing to Guid are not atomic, so I have to block them.

I decided to do it like this:

public Guid TestKey
{
    get
    {
        lock (_testKeyLock)
        {
            return _testKey;
        }
    }

    set
    {
        lock (_testKeyLock)
        {
            _testKey = value;
        }
    }
}

(Inside my class, all access to Guid is also through this property, and not directly with access to _testKey.)

I have two questions:

(1) Is it really necessary to block Guid so as to prevent breaking reads? (I'm sure it is.)

(2) Is this a smart way to do a lock? Or I need to do it like this:

get
{
    Guid result;

    lock (_testKeyLock)
    {
        result = _testKey;
    }

    return result;
}

[EDIT] This article confirms that Guides will suffer from gaps: http://msdn.microsoft.com/en-us/magazine/jj863136.aspx

+3
2

1) Guid , ? ( , .)

, .

2) ?

: .

Interlocked Guid, ().

double ( ) Interlocked, .

, , Interlocked.

+2

1: ; , ; Guid

2: " ": ; IL ret try/catch, , , .

; :

object boxedTestKey;
public Guid TestKey
{
    get { return (Guid)boxedTestKey; }
    set { boxedTestKey = value; }
}

, .

+7

Source: https://habr.com/ru/post/1662390/


All Articles