Fix write conflicts for disk session cache

Will use random waits when a write conflict is detected.
This should allow several clients to write at the same time.
Inspired from CSMA/CD (ethernet way of handling collisions).

Bug report by TNT-UP @ MC Forum post no.1684
This commit is contained in:
ORelio 2016-03-21 10:45:50 +01:00
parent 4a8b30ee94
commit 75bbeb0b4b
2 changed files with 27 additions and 11 deletions

View file

@ -156,22 +156,38 @@ namespace MinecraftClient.Protocol.SessionCache
private static void SaveToDisk() private static void SaveToDisk()
{ {
bool fileexists = File.Exists(SessionCacheFile); bool fileexists = File.Exists(SessionCacheFile);
IOException lastEx = null;
int attempt = 1;
using (FileStream fs = new FileStream(SessionCacheFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) while (attempt < 4)
{ {
cachemonitor.EnableRaisingEvents = false; try
// delete existing file contents
if (fileexists)
{ {
fs.SetLength(0); using (FileStream fs = new FileStream(SessionCacheFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
fs.Flush(); {
} cachemonitor.EnableRaisingEvents = false;
formatter.Serialize(fs, sessions); // delete existing file contents
cachemonitor.EnableRaisingEvents = true; if (fileexists)
{
fs.SetLength(0);
fs.Flush();
}
formatter.Serialize(fs, sessions);
cachemonitor.EnableRaisingEvents = true;
}
return;
}
catch (IOException ex)
{
lastEx = ex;
attempt++;
System.Threading.Thread.Sleep(new Random().Next(150, 350) * attempt); //CSMA/CD :)
}
} }
Console.WriteLine("Error writing cached sessions to disk" + (lastEx != null ? ": " + lastEx.Message : ""));
} }
} }
} }

View file

@ -112,7 +112,7 @@ If you are experienced with C#, you may also write a C# script.
That's a bit more involved, but way more powerful than regular scripts. That's a bit more involved, but way more powerful than regular scripts.
You can look to the provided sample C# scripts for getting started. You can look to the provided sample C# scripts for getting started.
C# scripts can be used for creating your own ChatBot without recompiling the wole project. C# scripts can be used for creating your own ChatBot without recompiling the whole project.
These bots are embedded in a script file, which is compiled and loaded on the fly. These bots are embedded in a script file, which is compiled and loaded on the fly.
ChatBots can access plugin channels for communicating with your own plugin. ChatBots can access plugin channels for communicating with your own plugin.