(1) In the below program if Swap and Iterate functions are called on two different threads, would it be safe to swap while collection is iterated on?
(2) Do I really need interlocked exchange as read/write to references are atomic (guaranteed by CLR), suppose Interlocked is required for release semantics for weak memory models?
class someClass
{
public void Swap()
{
Queue<SomeType> newQueue = new Queue<SomeType>();
var oldQueue = Interlocked.Exchange(ref queue, newQueue);
//Perform operation on old queue
}
public void Iterate()
{
foreach(var someTypeObject in queue)
{
//Do Something
}
}
Queue<SomeType> queue = new Queue<Sometype>();
}