My first thought was regarding SpinLock or Concurrent Collections
Lock Will work here as I tested, but it’s more expensive !
The Process here is based on Parallel Programming. And the task is running more than one in parallel.
During the SpinLock Version I encounter an error some times randomly saying similar to "Index out of range".
The SpinLock version which I wrote can’t do the job I wanted, Could any change be made on it to make it work ? or Isn’t it built for exactly related to this case ?
Any Info ?
Does it have any better alternative ?
This is what I did :
lock (lckRelatz)
{
relatz.Add(st);
}
And here is the SpinLock version – This is inside a method which is running in parallel :
SpinLock spinLk = new SpinLock();
bool gotLock = false;
try
{
spinLk.Enter(ref gotLock);
relatz.Add(st);
}
finally
{
if (gotLock)
spinLk.Exit();
}
It seems like you are creating new
SpinLockfor each thread. That will not actually lock anything. You need to have oneSpinLockand use that from all of your threads.But using a concurrent collection is even better solution. They are highly optimized and using them means you don’t have to worry about all the locking yourself.