I have an application that can be used by multiple users at the once. The application uses an API and its tokens need to be refreshed from time to time. The tokens are saved in a file. When the tokens need to be refreshed, the file is overwritten with the new tokens. My worry is that it is possible, in rare circumstances, that two instances of the application will try to write to the file at the exact same time. What happens then? I want to avoid a situation in which I am left with an empty file.
I have read other related questions and I've seen "the OS will schedule them" and "anything can happen". Which one is it?
Here are the 5 lines in question if it helps. Also, this currently isn't happening on a separate thread.
string newTokens = GetTokens();
using (StreamWriter writer = new StreamWriter("TokensFile.txt")) {
writer.Write(newTokens));
writer.Flush();
writer.Close();
}
The file will have whatever the last writer wrote to it. Giving the writer FileShare.ReadWrite
will allow multiple writers to use it:
string newTokens = GetTokens();
using (StreamWriter writer = new StreamWriter("TokensFile.txt", FileMode.Create, FileAccess.Write, FileShare.Readwrite)) {
writer.Write(newTokens));
writer.Flush();
writer.Close();
}