I know that there are .NET collections which are thread safe which I could use, but I still want to understand the following situation:
I have a Buffer class (below) which is used to writer data from a different thread, in a update loop interval (game) the main thread handles the data by swaping the list instance (to prevent both threads acting on the same instance at the same time).
So there is only a single additional thread who uses the "writerData" list, everything else is done on the main thread, but im not sure if the Swap method is thread "safe", because after searching for a while everyone seems to have a different opinion about swapping reference fields.
Some say that swapping reference doesn't require any locking other say that Interlocked.Exchange must be used in this case and other say it's not required, other say that the field must be violate and other say the keyword is "evil".
I know that threading is a difficult topic and maybe the other questions were too broad, but can someone help me to understand if any/which kind of "locking" is required in my specific case in the Swap method?
public class Buffer
{
List<byte> readerData;
List<byte> writerData; // This is the only field which is used by the other thread (by calling the Add method), well and by the Swap method, which is called from the main thread
// This method is only called by the other thread and it's the only method which is called from there
public void Add(byte data)
{
writerData.Add(data);
}
// Called on the main thread, before handling the readerData
public void Swap()
{
var tmp = readerData;
readerData = writerData
writerData = tmp;
}
// ... some other methods (which are only called from the main thread) to get the data from the (current) readerData field after calling the Swap method
}