Parcourir la source

WriteAtomic to retry if File.Replace fails

Brad Robinson il y a 7 ans
Parent
commit
b5cd31bbc5
1 fichiers modifiés avec 16 ajouts et 6 suppressions
  1. 16 6
      PetaJson.cs

+ 16 - 6
PetaJson.cs

@@ -148,13 +148,23 @@ namespace PetaJson
                     }
 
                     // Replace it
-                    try
-                    {
-                        File.Replace(tempName, filename, backupFilename);
-                    }
-                    catch (System.IO.IOException x)
+                    int retry = 0;
+                    while (true)
                     {
-                        throw new System.IO.IOException(string.Format("Failed to replace temp file {0} with {1} and backup {2}, reason {3}", tempName, filename, backupFilename, x.Message), x);
+                        try
+                        {
+                            File.Replace(tempName, filename, backupFilename);
+                            break;
+                        }
+                        catch (System.IO.IOException x)
+                        {
+                            retry++;
+                            if (retry >= 5)
+                            {
+                                throw new System.IO.IOException(string.Format("Failed to replace temp file {0} with {1} and backup {2}, reason {3}", tempName, filename, backupFilename, x.Message), x);
+                            }
+                            System.Threading.Thread.Sleep(2000);
+                        }
                     }
                 }
                 else