I have a large number of thumbnails to be rendered on a single webpage, and am trying to figure out the most efficient way from a resources perspective to return each image from the controller. My first thought was to await PhysicalFile, but PhysicalFile is not awaitable. That led me to the thought of wrapping PhysicalFile in Task.Run to be able to await it, which works:
[HttpGet("images/{imageName}")]
public async Task<IActionResult> Images(string imageName)
{
...
return await Task.Run(() => PhysicalFile(fullPath, "image/jpeg"));
}
This seems like a hack though, not to mention likely incurs overhead as a Task is created for each thumbnail.
The alternative, which looks cleaner, but is not asynchronous is this:
[HttpGet("images/{imageName}")]
public IActionResult Images(string imageName)
{
...
return PhysicalFile(fullPath, "image/jpeg");
}
Both solutions work, but which approach is the more efficient way from a resources perspective to accomplish this task?
Microsoft's documentation on PhysicalFile is lacking in details that would help clarify which approach is best.
CodePudding user response:
No, using Task.Run
is not the right thing to do here. Returning PhysicalFile as is, is enough. It returns an IActionResult
that has logic for writing the file to the response asynchronously.