访问由单独线程创建的文件
复制和访问文件时,我遇到多线程问题。
我有一个服务,它下载并解压 Zip 存档,然后将文件从解压缩的文件夹复制到正确的位置:
//Download, and uzip archive...
//Copy a needed file to its right location
File.Copy(fileName, fileDestination);
然后我启动一个单独的线程,需要访问复制的文件:
TheadPool.QueueUserWorkItem(s => processCopiedFile(fileDestination));
这是 ProcessCopiedFile 中的代码片段:
private void ProcessCopiedFile(string filePath)
{
...
//Load the file, previously copied here
var xml = XDocument.Load(filePath);
...
//Do other work...
}
XDoument .Load 调用失败并出现异常:
The process cannot access the file <FileName> because it is used by another process.
似乎 File.Copy 保持结果文件锁定。当所有工作同步进行时,它不会出现错误。 你有什么想法吗? 谢谢。
I have a problem aith multithreading when copying and accessing files.
I have a service, that downloads and unpacks a Zip archive, then it copies a file from unzipped folder to the right location:
//Download, and uzip archive...
//Copy a needed file to its right location
File.Copy(fileName, fileDestination);
Then I start a separate thread, that needs to access the copied files:
TheadPool.QueueUserWorkItem(s => processCopiedFile(fileDestination));
Here's the code fragment from ProcessCopiedFile:
private void ProcessCopiedFile(string filePath)
{
...
//Load the file, previously copied here
var xml = XDocument.Load(filePath);
...
//Do other work...
}
The XDoument.Load call fails with exception:
The process cannot access the file <FileName> because it is used by another process.
Seems like File.Copy keeps the result file locked. When do all work synchronuously, it works without errors.
Have you any thoughts?
Thx.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
File.Copy 不会保持任何打开或锁定的状态,它是一个原子操作,需要一些时间,当然取决于磁盘/网络 I/O 和文件大小。
当然,从同步转移到异步时,您应该确保在复制仍在进行时不会访问目标文件。
File.Copy does not keep anything open or locked, it is an atomic operation which requires some time, depending of course on Disk/Network I/O and file size.
Of course while moving from sync to async you should make sure you do not access the destination file while the copy is still in progress.
使用流复制文件以避免 File.Copy 的 Windows 锁定
Copy the file with a stream to avoid windows lock from File.Copy