Bit of a problem with a class I'm writing at the moment. I have it set up to write to file very regularly but in a single thread and currently I'm getting hit with the error message: The process cannot access the file because it is being used by another process. This happens regularly but not consistently - if I run it enough times it will break but there's no pattern as to when it breaks.
I've addressed all of the usual culprits here - I'm not using any System.Io.File methods which would return a FileStream so there's nothing that should need to be closed between calls. On top of that I'm testing a generic, single-threaded data structure class in a very stripped down environment - I'm certainly not using multi-threading intentionally and there's nothing in my debug windows to suggest that I'm using it unintentionally either. I'm working on files which exist only for the sake of this test, so I'm virtually 100% sure that nothing else is accessing them.
So I'm at a bit of a loss really. Any thoughts as to why this may be happening? If not, any suggestions as to an efficient workaround would also be appreciated.
Simplified Example
Main method:
static void Main(string[] args)
{
DiskMap<string> testMap = new DiskMap<string>("C:\path");
for (int i = 0; i < 100000; i++)
{
testMap.Add("a" + i, "aa" + i);
}
}
Class:
public class DiskMap<TValue>
{
private string path;
private int loadedDictionaryId;
private Dictionary<string, TValue> loadedDictionary;
public DiskMap(string path)
{
this.limit = limit;
this.path = path;
File.WriteAllText(path + "\\0.txt", "{");
File.WriteAllText(path + "\\1.txt", "{");
loadedDictionary = new Dictionary<string, TValue>();
loadedDictionaryId = 0;
}
public void Add(string key, TValue value)
{
int dictionaryId = GetId(key); // returns 0 or 1 in this example
if (dictionaryId == loadedDictId)
{
loadedDict.Add(key, value);
}
else
{
string filePath = this.path + "\\" + dictionaryId + ".txt";
File.AppendAllText(filePath, JsonConvert.SerializeObject(key) + ":" + JsonConvert.SerializeObject(value) + ","); // It breaks at this line
}
}
}