1

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.

DoodleKana
  • 2,106
  • 4
  • 27
  • 45
  • " when 2 *processes* tries to write at the same time" - one will fail with "already in use" exception... But it is probably not what you are asking as you've mentioned ASP.Net where multiple *requests* run in parallel in the same *process*... – Alexei Levenkov Apr 03 '14 at 16:18
  • @AlexeiLevenkov Correct, when I said process I meant to say multiple requests. – DoodleKana Apr 03 '14 at 16:33

1 Answers1

1

You could open it exclusively: How to lock file

You could put a lock on the handle used to open the file.

lock(File.OpenRead(myFileName))
{
  //do file operations
}
Community
  • 1
  • 1
Trisk
  • 593
  • 3
  • 8
  • I mentioned above that reading is not a problem. I can have simultanious read, but not for writing. Adding a lock is not enough, the requests that are trying to write to the file needs to wait when it is in use. I ended up using try catch and when the file is being accessed or used it will wait certain amount of time and try again until the lock is gone. then it will read again before writing to make sure it has the latest content of the file. – DoodleKana Apr 04 '14 at 15:18