File.Move原子操作 [英] File.Move atomic operation

查看:185
本文介绍了File.Move原子操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用C#生成一个巨大的文本文件,另一个进程是不断地看着位置,并试图拾取文件(如果可用)。



为了使文件原子在下面的步骤:

pre $ 1 $写入文件Filename_temp.txt
2检查是否Filename.txt已经存在然后删除
3 - 做一个File.Move到同一个目的地
从文件名:Filename_temp.txt
TO:Filename.txt
.com / b / adioltean / archive / 2005/12/28 / 507866.aspxrel =noreferrer>如何在文件中进行原子写入,重命名NTFS文件是一个原子操作:


解决方案?让我们记住元数据的变化是原子的。重命名就是这样的情况。所以,我们可以执行写入临时文件,并且在我们知道写入磁盘(完成并刷新)之后,我们可以将旧文件与新文件进行交换。

当然,这并不能保证 File.Move 只是发出NTFS重命名操作,但我想不出一个合理的理由,为什么它应该做更复杂的事情。


I am trying to generate a huge text file using C# and another process is constantly looking at the location and trying to pickup the file if available.

In order to make the file atomic below are the steps :

1 - Write to file : Filename_temp.txt
2 - Check if Filename.txt already exists then Delete
3 - Do a File.Move to the same destination     
    From filename : Filename_temp.txt 
    TO : Filename.txt

Since C# does not have a rename, I have to rely on File.Move, does this make sure the move operation will be atomic or is there another way to achieve this atomicity?

解决方案

According to the MSDN blog article How to do atomic writes in a file, renaming an NTFS file is an atomic operation:

The solution? Let's remember that metadata changes are atomic. Rename is such a case. So, we can just perform the write to a temporary file, and after we know that the writes are on the disk (completed and flushed) then we can interchange the old file with the new file.

Granted, this does not guarantee that File.Move just issues an NTFS rename operation, but I can't think of a valid reason why it should do anything more complicated.

这篇关于File.Move原子操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆