Generic Thread.VolatileRead and Thread.VolatileWrite

by Miha Markič 21. January 2010 20:41

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(ref T address)
{
    T result = address;
    Thread.MemoryBarrier();
    return result;
}

[MethodImpl(MethodImplOptions.NoInlining)]
public void VolatileWrite(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.



Tags: ,

.net | Parallel programming

Miha Markič

About me
Righthand
 
Microsoft MVP
 
Developer Express' DXSquad
INETA Country Leader for Slovenia
INETA Country Leader for Slovenia

Slovene Developer Users Group Lead
Friends of Red-Gate
LLBLGenPro Partner

Miha currently works as a free lance consultant and software developer specialized in .net area.
He graduated in Computer and information science at the University of Ljubljana, Slovenia. He has accumulated experience in various programming languages such as Java, Visual Basic 3-6 (MCP), Visual C++, Delphi, C# and VB.Net through years.
He has experience in practically all (technical) stages of project development, including planning, framework development, user interface, business processes, as well as testing and documenting. He has worked on big and small projects in Slovenia and abroad (e.g. participated in completing level 3 IS for the Nucor steel plant, Hertford, USA).
Currently he enjoys programming in .net environment using C#. Since 2000 he has been active in Developer Express' DX Squad and has been ECDL trainer and tester. He also gives lectures on conferences and other events in Slovenia.

Shortcuts

Add to Technorati Favorites

Social networking

Most comments

Electrolux Ergorapido Electrolux Ergorapido
1 comments
pr Puerto Rico
Holiday Travel Deals Holiday Travel Deals
1 comments
us United States
Marko Marko
1 comments
si Slovenia
olivier olivier
1 comments
fr France

Google friends

Recent Comments

Comment RSS