Generic Thread.VolatileRead and Thread.VolatileWrite

I am thinking about using a generic version of Thread.VolatileRead and Thread.VolatileWrite. The code is similar to existing one (actually there are plenty of overloads) with the difference of generic type parameter:

[MethodImpl(MethodImplOptions.NoInlining)]
public T VolatileRead<T>(ref T address)
{
    T result = address;
    Thread.MemoryBarrier();
    return result;
}

[MethodImpl(MethodImplOptions.NoInlining)]
public void VolatileWrite<T>(ref T address, T value)
{
    Thread.MemoryBarrier();
    address = value;
}

Why would I use generics if there is plenty of overloads already there? Because you have to perform casting to and from object since there is a single overload that accepts reference (ref object address that is). Here is an example:

Tubo tubo = new Tubo();
object param = tubo;
Tubo read = (Tubo)Thread.VolatileRead(ref param);

Isn’t the following code much better?

Tubo tubo = new Tubo();
Tubo read = MyThread.VolatileRead(ref tubo);

The questions is whether my code is correct or not. Sure it looks like correct but one never knows for sure when dealing with threading. Feedback appreciated.

Leave a Reply