I want to know if the following class is thread safe and works perfectly in multithread context?
public class ThreadSafeClass
{
private List<int> commandList = new List<int>();
public void AddCommand(int newCommand)
{
lock(syncObj) {
commandList.Add(newCommand);
}
}
public List<int> Split()
{
List<int> oldList = commandList;
commandList = new List<int>();
return oldList;
}
}
ThreadA periodically call split method, many thread call AddCommand, commandList in the split method is pointing to some list in memory and when the new list is assigned all of its content is in oldList
The purpose of split is that I want to get all of the queued commands and in the next call return rest of them, ... and meanwhile let the application add new items to commandList.
cause I focused on split method I forgot to add lock for add operation cause it is not thread-safe THANKS TO: (can poyrazoğlu) but the question remains for Split