I am implementing a class that will be used concurrently from multiple threads. Most of the properties get and set primitive types which can be handled properly by the Interlocked class. The class includes a Guid property. This is not as straight-forward to implement in a thread-safe manner. Is this how you would implement the 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: So the only proposed solution up to this point doesn’t include the use of any “Threading” classes or constructs. So I am going to pose the question that I’ve already posed in comments:
My understanding is that reference/primitive values types assignments are atomic however Interlocked will guarantee the change is propagated to all threads. If we could simply just assign the value, why does Interlocked expose APIs to exchange reference types and primitive values?
I think you could use the other overload of
Interlocked.Exchange:This works because the
Guidis now boxed, and the assignment of reference types is atomic.