访问由单独线程创建的文件

发布于 2024-12-11 21:20:42 字数 801 浏览 0 评论 0原文

复制和访问文件时,我遇到多线程问题。

我有一个服务,它下载并解压 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏见 2024-12-18 21:20:42

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.

花海 2024-12-18 21:20:42

使用流复制文件以避免 File.Copy 的 Windows 锁定

using(var s = new MemoryStream(File.ReadAllBytes(filePath))
{
    using(var fs = new FileStream(newLocation, FileMode.Create))
    {
        s.WriteTo(fs);
    }
}

Copy the file with a stream to avoid windows lock from File.Copy

using(var s = new MemoryStream(File.ReadAllBytes(filePath))
{
    using(var fs = new FileStream(newLocation, FileMode.Create))
    {
        s.WriteTo(fs);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文