Skip to content

Instantly share code, notes, and snippets.

@19WAS85
Last active December 17, 2015 07:09
Show Gist options
  • Save 19WAS85/5570614 to your computer and use it in GitHub Desktop.
Save 19WAS85/5570614 to your computer and use it in GitHub Desktop.
File persistent list.
public class PersistentList<T> : IList<T>
{
private static readonly object locker = new object();
private List<T> memoryList;
public PersistentList() : this(null) { }
public PersistentList(string filePath)
{
FilePath = filePath ?? String.Concat(Path.GetTempPath(), typeof(T).Name, ".list");
if (File.Exists(FilePath)) DeserializeThis();
else memoryList = new List<T>();
SerializeThis();
}
public string FilePath { get; private set; }
public void Add(T item)
{
Synchronized(list => list.Add(item));
}
public void Clear()
{
Synchronized(list => list.Clear());
}
public int IndexOf(T item)
{
return Synchronized(list => list.IndexOf(item));
}
public void Insert(int index, T item)
{
Synchronized(list => list.Insert(index, item));
}
public void RemoveAt(int index)
{
Synchronized(list => list.RemoveAt(index));
}
public T this[int index]
{
get { return Synchronized(list => list[index]); }
set { Synchronized(list => list[index] = value); }
}
public bool Contains(T item)
{
return Synchronized(list => list.Contains(item));
}
public void CopyTo(T[] array, int arrayIndex)
{
Synchronized(list => list.CopyTo(array, arrayIndex));
}
public int Count
{
get { return Synchronized(list => list.Count); }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T item)
{
return Synchronized(list => list.Remove(item));
}
public IEnumerator<T> GetEnumerator()
{
return Synchronized(list => list.GetEnumerator());
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private void SerializeThis()
{
using (var stream = new FileStream(FilePath, FileMode.OpenOrCreate))
{
new BinaryFormatter().Serialize(stream, memoryList);
}
}
private void DeserializeThis()
{
using (var stream = new FileStream(FilePath, FileMode.Open))
{
memoryList = (List<T>) new BinaryFormatter().Deserialize(stream);
}
}
private void Synchronized(Action<IList<T>> action)
{
lock (locker)
{
DeserializeThis();
action(memoryList);
SerializeThis();
}
}
private TResult Synchronized<TResult>(Func<IList<T>, TResult> function)
{
TResult value;
lock (locker)
{
DeserializeThis();
value = function(memoryList);
SerializeThis();
}
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment