Is this the right way to implement a read-write safe Guid property?

I am implementing a class that will be used simultaneously from multiple threads. Most properties get and set primitive types that can be correctly processed by the Interlocked class. The class includes the Guid property. This is not so straightforward to implement in a thread-safe manner. How to implement a property? Thanks in advance.

private Byte[] _activityId;
public Guid ActivityId 
    {
        get { return new Guid(this._activityId); }
        set
        {
            Byte[] bytes = value.ToByteArray();
            Interlocked.Exchange(ref this._activityId, bytes);
        }
    }

UPDATE: Thus, the only solution proposed so far does not include the use of any "Threading" classes or constructs. Therefore, I will try to ask a question that I already asked in the comments:

, / , Interlocked , . , Interlocked API ?

+5
2

, Interlocked.Exchange:

private volatile object _activityId; // Yes, object :)
public Guid ActivityId {
    get { return (Guid)_activityId; }
    set { _activityId = value; }
}

, Guid , .

+2

, :

class Box<T> where T : struct {
    public readonly T Value;
    public Box(T value) { Value = value; }
}

() Box , .

private Box<Guid> _activityId;
public Guid ActivityId {
    get { return this._activityId.Value; }
    set { this._activityId = new Box<Guid>(value); }
}

, new Box<Guid>(value) .Value. , .

, -, , . ( : )

+4

All Articles