Skip to content

Async IO methods should use FileOptions.Asynchronous #2487

Description

@Neme12

Prerequisites

  • I have written a descriptive issue title
  • I have verified that I am running the latest version of ImageSharp
  • I have verified if the problem exist in both DEBUG and RELEASE mode
  • I have searched open and closed issues to ensure it has not already been reported

ImageSharp version

3.0.1

Environment (Operating system, version and so on)

Windows 11 Version 22H2

.NET Framework version

.NET 7.0.304

Description

Async methods that read/write from the file system, such as Image.LoadAsync and Image.SaveAsync, use async methods on FileStream but don't instantiate the FileStream with FileOptions.Asynchronous, as should be done when using async operations. This means that the implementation isn't actually truly async and instead uses synchronous IO on a new thread, needlessly using more resources.

There is a simple workaround for this by creating the FileStream manually and giving ImageSharp the stream as opposed to the file path, e.g.:

await using (var fileStream = new FileStream(path, new FileStreamOptions
{
    Mode = FileMode.Open,
    Access = FileAccess.Read,
    Share = FileShare.Read,
    Options = FileOptions.Asynchronous,
}))
using (var image = await Image.LoadAsync(fileStream))
{
// ...
}

but I feel like this is a bug and should be fixed in ImageSharp itself. The method is misleading, suggesting that it uses async IO while actually doesn't.

Activity

  1. antonfirsov commented on Jun 30, 2023

    @antonfirsov
    Member

    This makes sense, here is what BCL is doing for File.ReadAllTextAsync:

    https://github.com/dotnet/runtime/blob/2f208128f257b2390a8edefa0a19e0eaad6bd419/src/libraries/System.Private.CoreLib/src/System/IO/File.cs#L853-L856

    I guess SequentialScan would make things worse in our case, because BufferedReadStream does Seek a lot.

    @Neme12 interested creating a PR?

  2. Neme12 commented on Jun 30, 2023

    @Neme12
    ContributorAuthor

    Sure, I can give it a try.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions