dotnet/runtime

Identify places where file handles are closed and very soon reopened again

Open

#64,288 建立於 2022年1月25日

在 GitHub 查看
 (1 留言) (2 反應) (0 負責人)C# (5,445 fork)batch import
area-System.IOhelp wanted

倉庫指標

Star
 (17,886 star)
PR 合併指標
 (平均合併 12天 11小時) (30 天內合併 661 個 PR)

描述

As https://github.com/dotnet/runtime/pull/63912 has shown, there are places in BCL where files are being closed and very soon reopened (it's typically not obvious).

using (FileStream fs = new FileStream(destinationFileName, fMode, FileAccess.Write, FileShare.None, bufferSize: 0x1000, useAsync: false))
{
    using (Stream es = source.Open())
        es.CopyTo(fs);
} // the file is closed

File.SetLastWriteTime(destinationFileName, source.LastWriteTime.DateTime); // it's reopened

It causes two kinds of problems:

  • AV and other software can open the file in the meantime, lock the access and hence make the re-opening code fail (ERROR_SHARING_VIOLATION on Windows)
  • the perf is not ideal, as opening the files is expensive (especially on Unix where we perform more than 1 sys-call to open a file).

One of the potential solutions would be to use APIs that are accepting SafeFileHandle like https://github.com/dotnet/runtime/issues/20234

貢獻者指南