file read&write concurrency issue solution

In C#, if 2 processes are reading and writing to the same file, what is the best way to avoid process locking exceptions?

http://stackoverflow.com/questions/222089/in-c-if-2-processes-are-reading-and-writing-to-the-same-file-what-is-the-best

 

 

Solution:

 

 

You can open a file for writing and only lock write access, thereby allowing others to still read the file.

For example,

using (FileStream stream = new FileStream(@"C:/Myfile.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
   // Do your writing here.
}

Other file access just opens the file for reading and not writing, and allows readwrite sharing.

using (FileStream stream = new FileStream(@"C:/Myfile.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
   // Does reading  here.
}

If you want to ensure that readers will always read an up-to-date file, you will either need to use a locking file that indicates someone is writing to the file (though you may get a race condition if not carefully implemented) or make sure you block write-sharing when opening to read and handle the exception so you can try again until you get exclusive access.
link|flag
   
edited Oct 21 '08 at 14:58

   
answered Oct 21 '08 at 14:35
Jeff Yates
16.1k22665
   
   
But in this case, if I understand the workings correctly, you could read an incomplete file? – Mitchel Sellers Oct 21 '08 at 14:46
   
That is true, yes. That's always going to be the case if you allow more than one consumer to access the file. The only way to achieve this and synchronize is to either use a lock file, or to catch the access exception and try again until you get exclusive access. – Jeff Yates Oct 21 '08 at 14:56

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值