code_junkie

Want to write to a file, but may have potentially multiple writers at once, need to lock

Nov 10th, 2011
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.66 KB | None | 0 0
  1. lock(this)
  2. {
  3. // perform the write.
  4. }
  5.  
  6. // try enter will return false if another thread owns the lock
  7. if (Monitor.TryEnter(lockObj))
  8. {
  9. try
  10. {
  11. // check last write time here, return if too soon; otherwise, write
  12. }
  13. finally
  14. {
  15. Monitor.Exit(lockobj);
  16. }
  17. }
  18.  
  19. FileInfo fi = new FileInfo(path);
  20. if (fi.Exists
  21. && (DateTime.UtcNow - fi.LastWriteTimeUtc < TimeSpan.FromMinutes(15)) {
  22. // file is fresh
  23. return;
  24. }
  25.  
  26. FileStream fs;
  27. try {
  28. fs = new FileStream(
  29. path, FileMode.Create, FileAccess.Write, FileShare.Read);
  30. } catch (IOException) {
  31. // file is locked
  32. return;
  33. }
  34.  
  35. using (fs) {
  36. // write to file
  37. }
Add Comment
Please, Sign In to add comment