浏览代码

WriteAtomic to retry if File.Replace fails

Brad Robinson 7 年之前
父节点
当前提交
b5cd31bbc5
共有 1 个文件被更改,包括 16 次插入6 次删除
  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