I have a json file that will be accessed by web api service. I want to make sure that no two or more web requests will try to write to the file at the same time.
Below code is my webapi controller code. Basically when it gets a request it will read the existing json file and deserializes it and adds new item to the list and writes it back to the json file. I believe the reading part is fine for simultanious read. Because I am writing the entire list to the file again, I wonder what will happen when 2 processes tries to write at the same time. How do I put a lock on the file or something, so one process waits to write to json file and then once lock is gone the other process resumes to write?
using (StreamReader r = new StreamReader(File.OpenRead(myfilename)))
{
string jsonData = r.ReadToEnd();
someList = JsonConvert.DeserializeObject<List<MyData>>(jsonData);
}
someList.Add(newItem);
using (var sw = new StreamWriter(myfilename))
{
using (JsonWriter jw = new JsonTextWriter(sw))
{
jw.Formatting = Formatting.Indented;
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(jw, someList);
}
}
BTW: there will be only one type of web api code that will be writing to this file. But multiple web requests will be made to that same web api.