Last active
March 19, 2020 15:32
-
-
Save tugberkugurlu/a5a65602e30260eef00b to your computer and use it in GitHub Desktop.
C# Atomic File Write Sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Text; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace AtomicWriteSample | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
string filePath = Path.Combine(Path.GetTempPath(), "foo.txt"); | |
Parallel.For(0, 10, new ParallelOptions() { MaxDegreeOfParallelism = 10 }, i => | |
{ | |
byte[] fileContent = Encoding.UTF8.GetBytes("hello there: " + i.ToString()); | |
using (Stream stream = new MemoryStream(fileContent)) | |
{ | |
try | |
{ | |
WriteFile(filePath, stream); | |
Console.WriteLine("Winner: " + i.ToString() + ", ThreadId: " + Thread.CurrentThread.ManagedThreadId); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine(ex.Message + ": " + i.ToString() + ", ThreadId: " + Thread.CurrentThread.ManagedThreadId); | |
} | |
} | |
}); | |
Console.ReadLine(); | |
} | |
static void WriteFile(string filePath, Stream fileStream) | |
{ | |
string tempFilePath = Path.GetTempFileName(); | |
using (FileStream tempFile = File.OpenWrite(tempFilePath)) | |
{ | |
fileStream.CopyTo(tempFile); | |
} | |
try | |
{ | |
File.Move(tempFilePath, filePath); | |
} | |
catch (Exception ex) | |
{ | |
try | |
{ | |
File.Delete(tempFilePath); | |
} | |
catch (Exception) | |
{ | |
Console.WriteLine("cannot delete as well!!!"); | |
} | |
throw; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment